Example #1
0
File: lua.c Project: Cynede/hexchat
static void check_deferred(script_info *info)
{
	info->status &= ~STATUS_ACTIVE;
	if(info->status & STATUS_DEFERRED_UNLOAD)
	{
		run_unload_hooks(info, NULL);
		g_ptr_array_remove_fast(scripts, info);
	}
	else if(info->status & STATUS_DEFERRED_RELOAD)
	{
		if(info == interp)
		{
			run_unload_hooks(interp, NULL);
			destroy_interpreter();
			create_interpreter();
		}
		else
		{
			char *filename = g_strdup(info->filename);
			run_unload_hooks(info, NULL);
			g_ptr_array_remove_fast(scripts, info);
			load_script(filename);
			g_free(filename);
		}
	}
}
Example #2
0
void
graph_remove_edge (Graph *self, GraphEdge *edge)
{
  gboolean found_edge = g_ptr_array_remove_fast (self->edges, edge);
  g_assert (found_edge);
  found_edge = g_ptr_array_remove_fast (edge->from_node->out_edges, edge);
  g_assert (found_edge);
  found_edge = g_ptr_array_remove_fast (edge->to_node->in_edges, edge);
  g_assert (found_edge);
  g_free (edge);
}
Example #3
0
File: io.c Project: TaylanUB/uzbl
gboolean
remove_socket_from_array(GIOChannel *chan) {
    gboolean ret = 0;

    ret = g_ptr_array_remove_fast(uzbl.comm.connect_chan, chan);
    if(!ret)
        ret = g_ptr_array_remove_fast(uzbl.comm.client_chan, chan);

    if(ret)
        g_io_channel_unref (chan);
    return ret;
}
Example #4
0
File: lua.c Project: Cynede/hexchat
static int unregister_hook(hook_info *hook)
{
	script_info *info = get_info(hook->state);

	if(g_ptr_array_remove_fast(info->hooks, hook))
		return 1;

	if(g_ptr_array_remove_fast(info->unload_hooks, hook))
		return 1;

	return 0;
}
Example #5
0
void
flow_joiner_remove_input_pad (FlowJoiner *joiner, FlowInputPad *input_pad)
{
  FlowElement *element = (FlowElement *) joiner;
  gboolean     was_removed;

  g_return_if_fail (FLOW_IS_JOINER (joiner));
  g_return_if_fail (FLOW_IS_INPUT_PAD (input_pad));

  if (element->dispatch_depth)
  {
    was_removed = flow_g_ptr_array_remove_sparse (element->input_pads, input_pad);
    element->input_pad_removed = TRUE;  /* Can't use was_removed because it may already be TRUE */
  }
  else
  {
    was_removed = g_ptr_array_remove_fast (element->input_pads, input_pad);
  }

  if (!was_removed)
  {
    g_warning ("Tried to remove unknown input pad from joiner!");
    return;
  }

  element->pending_inputs = g_slist_remove (element->pending_inputs, input_pad);
  g_object_unref (input_pad);
}
Example #6
0
static void
remove_wsq (MonoWSQ *wsq)
{
	gpointer data;

	if (wsq == NULL)
		return;

	EnterCriticalSection (&wsqs_lock);
	if (wsqs == NULL) {
		LeaveCriticalSection (&wsqs_lock);
		return;
	}
	g_ptr_array_remove_fast (wsqs, wsq);
	data = NULL;
	/*
	 * Only clean this up when shutting down, any other case will error out
	 * if we're removing a queue that still has work items.
	 */
	if (mono_runtime_is_shutting_down ()) {
		while (mono_wsq_local_pop (&data)) {
			threadpool_jobs_dec (data);
			data = NULL;
		}
	}
	mono_wsq_destroy (wsq);
	LeaveCriticalSection (&wsqs_lock);
}
/**
 * gst_vaapi_surface_associate_subpicture:
 * @surface: a #GstVaapiSurface
 * @subpicture: a #GstVaapiSubpicture
 * @src_rect: the sub-rectangle of the source subpicture
 *   image to extract and process. If %NULL, the entire image will be used.
 * @dst_rect: the sub-rectangle of the destination
 *   surface into which the image is rendered. If %NULL, the entire
 *   surface will be used.
 *
 * Associates the @subpicture with the @surface. The @src_rect
 * coordinates and size are relative to the source image bound to
 * @subpicture. The @dst_rect coordinates and size are relative to the
 * target @surface. Note that the @surface holds an additional
 * reference to the @subpicture.
 *
 * Return value: %TRUE on success
 */
gboolean
gst_vaapi_surface_associate_subpicture (GstVaapiSurface * surface,
    GstVaapiSubpicture * subpicture,
    const GstVaapiRectangle * src_rect, const GstVaapiRectangle * dst_rect)
{
  gboolean success;

  g_return_val_if_fail (surface != NULL, FALSE);
  g_return_val_if_fail (subpicture != NULL, FALSE);

  if (!surface->subpictures) {
    surface->subpictures = g_ptr_array_new ();
    if (!surface->subpictures)
      return FALSE;
  }

  if (g_ptr_array_remove_fast (surface->subpictures, subpicture)) {
    success = _gst_vaapi_surface_deassociate_subpicture (surface, subpicture);
    gst_vaapi_object_unref (subpicture);
    if (!success)
      return FALSE;
  }

  success = _gst_vaapi_surface_associate_subpicture (surface,
      subpicture, src_rect, dst_rect);
  if (!success)
    return FALSE;

  g_ptr_array_add (surface->subpictures, gst_vaapi_object_ref (subpicture));
  return TRUE;
}
/**
 * gst_vaapi_surface_deassociate_subpicture:
 * @surface: a #GstVaapiSurface
 * @subpicture: a #GstVaapiSubpicture
 *
 * Deassociates @subpicture from @surface. Other associations are kept.
 *
 * Return value: %TRUE on success
 */
gboolean
gst_vaapi_surface_deassociate_subpicture (GstVaapiSurface * surface,
    GstVaapiSubpicture * subpicture)
{
  gboolean success;

  g_return_val_if_fail (surface != NULL, FALSE);
  g_return_val_if_fail (subpicture != NULL, FALSE);

  if (!surface->subpictures)
    return TRUE;

  /* First, check subpicture was really associated with this surface */
  if (!g_ptr_array_remove_fast (surface->subpictures, subpicture)) {
    GST_DEBUG ("subpicture %" GST_VAAPI_ID_FORMAT " was not bound to "
        "surface %" GST_VAAPI_ID_FORMAT,
        GST_VAAPI_ID_ARGS (GST_VAAPI_OBJECT_ID (subpicture)),
        GST_VAAPI_ID_ARGS (GST_VAAPI_OBJECT_ID (surface)));
    return TRUE;
  }

  success = _gst_vaapi_surface_deassociate_subpicture (surface, subpicture);
  gst_vaapi_object_unref (subpicture);
  return success;
}
Example #9
0
void
ipc_endpoint_connect_to_socket(ipc_endpoint_t *ipc, int sock)
{
    g_assert(ipc);
    g_assert(ipc->status == IPC_ENDPOINT_DISCONNECTED);

    ipc_recv_state_t *state = &ipc->recv_state;
    state->queued_ipcs = g_ptr_array_new();

    GIOChannel *channel = g_io_channel_unix_new(sock);
    g_io_channel_set_encoding(channel, NULL, NULL);
    g_io_channel_set_buffered(channel, FALSE);
    state->watch_in_id = g_io_add_watch(channel, G_IO_IN, (GIOFunc)ipc_recv, ipc);
    state->watch_hup_id = g_io_add_watch(channel, G_IO_HUP, (GIOFunc)ipc_hup, ipc);

    /* Atomically update ipc->channel. This is done because on the web extension
     * thread, logging spawns a message send thread, which may attempt to write
     * to the uninitialized channel after it has been created with
     * g_io_channel_unix_new(), but before it has been set up fully */
    g_atomic_pointer_set(&ipc->channel, channel);

    ipc->status = IPC_ENDPOINT_CONNECTED;

    if (!endpoints)
        endpoints = g_ptr_array_sized_new(1);

    /* Add the endpoint; it should never be present already */
    g_assert(!g_ptr_array_remove_fast(endpoints, ipc));
    g_ptr_array_add(endpoints, ipc);
}
Example #10
0
void unregister_ability(Client *cli, const gchar *func)
{
    GPtrArray *workers = g_hash_table_lookup(g_workers, func);
    if (workers) {
        g_ptr_array_remove_fast(workers, cli);
    }
    client_remove_ability(cli, func);
}
Example #11
0
// remove from a channel's handler list
static void 
map_remove_handler_callback(gpointer _key, gpointer _value, 
        gpointer _data)
{
    lcm_subscription_t *h = (lcm_subscription_t*) _data;
    GPtrArray *handlers = (GPtrArray*) _value;
    g_ptr_array_remove_fast(handlers, h);
}
Example #12
0
static gint gv_manager_raster_destroy_cb( GObject * raster_in,
        gpointer cb_data )
{
    GvManager *manager = GV_MANAGER(cb_data);
    GvRaster  *raster = GV_RASTER(raster_in);
    GvDataset *ds = NULL;
    int       i, active_rasters = 0;

    /*
     * Find in our list.  The dataset must already be "under management".
     */
    for( i = 0; i < manager->datasets->len; i++ )
    {
        ds = (GvDataset *) g_ptr_array_index(manager->datasets, i);

        if( raster->dataset == ds->dataset )
            break;
    }

    if( i == manager->datasets->len )
    {
        g_warning( "gv_manager_raster_destroy_cb(): can't find dataset." );
        return FALSE;
    }

    /*
     * Find our GvRaster.
     */

    for( i = 0; i < GDALGetRasterCount(ds->dataset); i++ )
    {
        if( ds->rasters[i] == raster ) {
            /* MB: still not sure if we need to unref here... */
//            if (G_OBJECT(raster)->ref_count > 1)
//                g_object_unref(ds->rasters[i]);
            ds->rasters[i] = NULL;
        }
        else if( ds->rasters[i] != NULL )
            active_rasters++;
    }

    /*
     * We apparently no longer need this GDALDataset.  Dereference it, and
     * remove from the list.
     */
    if (active_rasters == 0)
    {
        if (GDALDereferenceDataset(ds->dataset) < 1) {
            GDALClose(ds->dataset);
        }

        g_free(ds->rasters);
        g_free(ds);
        g_ptr_array_remove_fast(manager->datasets, ds);
    }

    return FALSE;
}
Example #13
0
int return_mem_block(mem_superblock_t *msb, void *p) {
	unsigned int i;
	for (i=0; i<msb->blocks->len; i++) {
		mem_block_t *mb=g_ptr_array_index(msb->blocks,i);
		if (g_ptr_array_remove_fast(mb->used, p)==TRUE) {
            g_ptr_array_add(mb->free,p);
            return 0;
        }
    }
	return -1;	
}
Example #14
0
void
graph_remove_node (Graph *self, GraphNode *node)
{
  // IMPROVEME: for symmetry it might be nice to have a
  // graph_node_free method.
  g_assert (node->in_edges->len == 0 && node->out_edges->len == 0);
  g_ptr_array_free (node->out_edges, TRUE);
  g_ptr_array_free (node->in_edges, TRUE);
  gboolean found_node = g_ptr_array_remove_fast (self->nodes, node);
  g_free (node);
  g_assert (found_node);
}
/**
 * media_channel_closed_cb:
 * Signal callback for when a media channel is closed. Removes the references
 * that #RakiaMediaManager holds to them.
 */
static void
call_channel_closed_cb (RakiaCallChannel *chan, gpointer user_data)
{
  RakiaMediaManager *fac = RAKIA_MEDIA_MANAGER (user_data);
  RakiaMediaManagerPrivate *priv = RAKIA_MEDIA_MANAGER_GET_PRIVATE (fac);

  tp_channel_manager_emit_channel_closed_for_object (fac,
      TP_EXPORTABLE_CHANNEL (chan));

  if (priv->channels)
    {
      g_ptr_array_remove_fast (priv->channels, chan);
    }
}
/**
 * ggn_account_list_accounts_clear:
 * @alist: The account list to modify.
 *
 * Clears the entries #GPtrArray of a given #GgnAccountList. private only.
 *
 * Returns: void.
 **/
void ggn_account_list_accounts_clear (GgnAccountList *alist) {
  /* define a helping variable. */
  gpointer ptr;

  /* loop until the pointer array is empty. */
  while (alist->priv->accounts->len > 0) {
    /* remove the first pointer. */
    ptr = g_ptr_array_index (alist->priv->accounts, 0);
    g_ptr_array_remove_fast (alist->priv->accounts, ptr);

    /* free the entry (pointer). */
    ggn_account_free ((GgnAccount *) ptr);
  }
}
static void
content_ready (GObject *object, GAsyncResult *res, gpointer user_data)
{
  TfCallChannel *self = TF_CALL_CHANNEL (user_data);
  TfCallContent *content = TF_CALL_CONTENT (object);

  if (g_async_initable_init_finish (G_ASYNC_INITABLE (object), res, NULL))
    {
      g_signal_emit (self, signals[SIGNAL_CONTENT_ADDED], 0, content);
    }
  else
    {
      g_ptr_array_remove_fast (self->contents, content);
    }

  g_object_unref (self);
}
static void _downloadmanager_download_free(downloadmanager_t* pDownloadManager, download_t* pDownload)
{
	// Empty struct
	g_free(pDownload->pszRemoteFilePath);
	g_free(pDownload->pszLocalFilePath);
	if(pDownload->pGnomeVFSHandle != NULL) {
		// XXX: do we need to close this?
		// gnome_vfs_async_close(pDownload->pGnomeVFSHandle, _downloader_gnome_vfs_close_callback, NULL);
	}

	// XXX: store a 'state' so we know which array it's in?
	g_ptr_array_remove_fast(pDownloadManager->pActiveArray, pDownload);
	g_ptr_array_remove(pDownloadManager->pPendingArray, pDownload);

	// Free struct
	g_free(pDownload);
}
/**
 * asb_plugin_appdata_remove_file:
 */
static void
asb_plugin_appdata_remove_file (AsbPlugin *plugin, const gchar *filename)
{
	const gchar *tmp;
	guint i;

	g_mutex_lock (&plugin->priv->filenames_mutex);
	for (i = 0; i < plugin->priv->filenames->len; i++) {
		tmp = g_ptr_array_index (plugin->priv->filenames, i);
		if (g_strcmp0 (tmp, filename) == 0) {
			g_ptr_array_remove_fast (plugin->priv->filenames,
						 (gpointer) tmp);
			break;
		}
	}
	g_mutex_unlock  (&plugin->priv->filenames_mutex);
}
Example #20
0
File: lua.c Project: Cynede/hexchat
static int unload_script(char const *filename)
{
	script_info *script = get_script_by_file(filename);

	if (!script)
		return 0;

	if(script->status & STATUS_ACTIVE)
		script->status |= STATUS_DEFERRED_UNLOAD;
	else
	{
		run_unload_hooks(script, NULL);
		g_ptr_array_remove_fast(scripts, script);
	}

	return 1;

}
Example #21
0
void stop_all_listening(Client *cli)
{
    if (!cli->listening)
        return;

    int i;
    Job *job;
    for(i = 0; i < cli->listening->len; i++) {
        job = g_ptr_array_index(cli->listening, i);
        g_ptr_array_remove_fast(job->listeners, cli);
        if (!job->background && job->listeners->len == 0) {
            #if DEBUG
            g_debug("[%s] removing non-background job with no listeners: %s", cli->id, job->handle);
            #endif
            remove_job(job);
        }
    }
    client_clear_listening(cli);
}
static void
clipman_free (XfcePanelPlugin *plugin,
              ClipmanPlugin   *clipman)
{
    guint        i;
    ClipmanClip *clip;
    GtkWidget   *dialog;

    dialog = g_object_get_data (G_OBJECT (plugin), "dialog");

    if (dialog)
        gtk_widget_destroy (dialog);

    /* Stop the check loop */
    clipman->killTimeout = TRUE;
    if (clipman->TimeoutId != 0)
    {
        g_source_remove(clipman->TimeoutId);
        clipman->TimeoutId = 0;
    }
    
    /* Remove clipboard items */
    for (i = clipman->clips->len; i--;)
    {
        clip = g_ptr_array_index (clipman->clips, i);
        g_ptr_array_remove_fast (clipman->clips, clip);
        clipman_free_clip (clip);
    }
    g_ptr_array_free (clipman->clips, TRUE);

    gtk_tooltips_set_tip (clipman->tooltip, clipman->button, NULL, NULL);
    g_object_unref (clipman->tooltip);
    
    gtk_widget_destroy (clipman->icon);
    gtk_widget_destroy (clipman->button);
    
    clipman->plugin = NULL;
    
    DBG ("Plugin Freed");
    
    g_free (clipman);
}
Example #23
0
File: lua.c Project: Cynede/hexchat
static int reload_script(char const *filename)
{
	script_info *script = get_script_by_file(filename);

	if (!script)
		return 0;

	if(script->status & STATUS_ACTIVE)
	{
		script->status |= STATUS_DEFERRED_RELOAD;
	}
	else
	{
		char *filename = g_strdup(script->filename);
		run_unload_hooks(script, NULL);
		g_ptr_array_remove_fast(scripts, script);
		load_script(filename);
		g_free(filename);
	}

	return 1;
}
Example #24
0
static void
egg_state_machine__style_object_weak_notify (gpointer  data,
                                             GObject  *where_object_was)
{
  EggStateStyle *style_prop = data;
  EggStateMachine *self = style_prop->state_machine;
  EggStateMachinePrivate *priv = egg_state_machine_get_instance_private (self);
  GHashTableIter iter;
  EggState *state;

  g_assert (EGG_IS_STATE_MACHINE (self));
  g_assert (where_object_was != NULL);

  style_prop->widget = NULL;

  g_hash_table_iter_init (&iter, priv->states);
  while (g_hash_table_iter_next (&iter, NULL, (gpointer)&state))
    {
      if (g_ptr_array_remove_fast (state->styles, style_prop))
        return;
    }

  g_critical ("Failed to find style for %p", where_object_was);
}
Example #25
0
RESULT ptrarray_remove_fast()
{
	GPtrArray *array = g_ptr_array_new();
	gchar *letters [] = { "A", "B", "C", "D", "E" };
	
	if (g_ptr_array_remove_fast (array, NULL))
		return FAILED ("Removing NULL succeeded");

	g_ptr_array_add(array, letters[0]);
	if (!g_ptr_array_remove_fast (array, letters[0]) || array->len != 0)
		return FAILED ("Removing last element failed");

	g_ptr_array_add(array, letters[0]);
	g_ptr_array_add(array, letters[1]);
	g_ptr_array_add(array, letters[2]);
	g_ptr_array_add(array, letters[3]);
	g_ptr_array_add(array, letters[4]);

	if (!g_ptr_array_remove_fast (array, letters[0]) || array->len != 4)
		return FAILED ("Removing first element failed");

	if (array->pdata [0] != letters [4])
		return FAILED ("First element wasn't replaced with last upon removal");

	if (g_ptr_array_remove_fast (array, letters[0]))
		return FAILED ("Succedeed removing a non-existing element");

	if (!g_ptr_array_remove_fast (array, letters[3]) || array->len != 3)
		return FAILED ("Failed removing \"D\"");

	if (!g_ptr_array_remove_fast (array, letters[1]) || array->len != 2)
		return FAILED ("Failed removing \"B\"");

	if (array->pdata [0] != letters [4] || array->pdata [1] != letters [2])
		return FAILED ("Last two elements are wrong");
	g_ptr_array_free(array, TRUE);
	
	return OK;
}
Example #26
0
static void
fs_rtp_conference_handle_message (
    GstBin * bin,
    GstMessage * message)
{
  FsRtpConference *self = FS_RTP_CONFERENCE (bin);

  if (!self->rtpbin)
    goto out;

  switch (GST_MESSAGE_TYPE (message)) {
    case GST_MESSAGE_ELEMENT:
    {
      const GstStructure *s = gst_message_get_structure (message);

      /* we change the structure name and add the session ID to it */
      if (gst_structure_has_name (s, "application/x-rtp-source-sdes") &&
          gst_structure_has_field_typed (s, "session", G_TYPE_UINT) &&
          gst_structure_has_field_typed (s, "ssrc", G_TYPE_UINT) &&
          gst_structure_has_field_typed (s, "cname", G_TYPE_STRING))
      {
        guint session_id;
        guint ssrc;
        const GValue *val;
        FsRtpSession *session;
        const gchar *cname;

        val = gst_structure_get_value (s, "session");
        session_id = g_value_get_uint (val);

        val = gst_structure_get_value (s, "ssrc");
        ssrc = g_value_get_uint (val);

        cname = gst_structure_get_string (s, "cname");

        if (!ssrc || !cname)
        {
          GST_WARNING_OBJECT (self,
              "Got GstRTPBinSDES without a ssrc or a cname (ssrc:%u cname:%p)",
              ssrc, cname);
          break;
        }

        session = fs_rtp_conference_get_session_by_id (self, session_id);

        if (session) {
          fs_rtp_session_associate_ssrc_cname (session, ssrc, cname);
          g_object_unref (session);
        } else {
          GST_WARNING_OBJECT (self,"Our RtpBin announced a new association"
              "for non-existent session %u for ssrc: %u and cname %s",
              session_id, ssrc, cname);
        }
      }
      else if (gst_structure_has_name (s, "dtmf-event-processed") ||
          gst_structure_has_name (s, "dtmf-event-dropped"))
      {
        GList *item;
        guint cookie;


        GST_OBJECT_LOCK (self);
      restart:
        cookie = self->priv->sessions_cookie;
        for (item = self->priv->sessions; item; item = item->next)
        {
          GST_OBJECT_UNLOCK (self);
          if (fs_rtp_session_handle_dtmf_event_message (item->data, message))
          {
            gst_message_unref (message);
            message = NULL;
            goto out;
          }
          GST_OBJECT_LOCK (self);
          if (cookie != self->priv->sessions_cookie)
            goto restart;
        }
        GST_OBJECT_UNLOCK (self);

      }
    }
    break;
    case GST_MESSAGE_STREAM_STATUS:
    {
      GstStreamStatusType type;
      guint i;

      gst_message_parse_stream_status (message, &type, NULL);

      switch (type)
      {
        case GST_STREAM_STATUS_TYPE_ENTER:
          GST_OBJECT_LOCK (self);
          for (i = 0; i < self->priv->threads->len; i++)
          {
            if (g_ptr_array_index (self->priv->threads, i) ==
                g_thread_self ())
              goto done;
          }
          g_ptr_array_add (self->priv->threads, g_thread_self ());
        done:
          GST_OBJECT_UNLOCK (self);
          break;

        case GST_STREAM_STATUS_TYPE_LEAVE:
          GST_OBJECT_LOCK (self);
          while (g_ptr_array_remove_fast (self->priv->threads,
                  g_thread_self ()));
          GST_OBJECT_UNLOCK (self);
          break;

        default:
          /* Do nothing */
          break;
      }
    }
      break;
    default:
      break;
  }

 out:
  /* forward all messages to the parent */
  if (message)
    GST_BIN_CLASS (fs_rtp_conference_parent_class)->handle_message (bin,
        message);
}
Example #27
0
void li_stat_cache_entry_release(liVRequest *vr, liStatCacheEntry *sce) {
    g_ptr_array_remove_fast(sce->vrequests, vr);
    g_ptr_array_remove_fast(vr->stat_cache_entries, sce);
    stat_cache_entry_release(sce);
}
Example #28
0
static void
async_invoke_thread (gpointer data)
{
	MonoDomain *domain;
	MonoWSQ *wsq;
	ThreadPool *tp;
	gboolean must_die;
  
	tp = data;
	wsq = NULL;
	if (!tp->is_io)
		wsq = add_wsq ();

	set_tp_thread_info (tp);

	if (tp_start_func)
		tp_start_func (tp_hooks_user_data);

	data = NULL;
	for (;;) {
		MonoAsyncResult *ar;
		MonoClass *klass;
		gboolean is_io_task;
		gboolean is_socket;
		int n_naps = 0;

		is_io_task = FALSE;
		ar = (MonoAsyncResult *) data;
		if (ar) {
			InterlockedIncrement (&tp->busy_threads);
			domain = ((MonoObject *)ar)->vtable->domain;
#ifndef DISABLE_SOCKETS
			klass = ((MonoObject *) data)->vtable->klass;
			is_io_task = !is_corlib_asyncresult (domain, klass);
			is_socket = FALSE;
			if (is_io_task) {
				MonoSocketAsyncResult *state = (MonoSocketAsyncResult *) data;
				is_socket = is_socketasyncresult (domain, klass);
				ar = state->ares;
				switch (state->operation) {
				case AIO_OP_RECEIVE:
					state->total = ICALL_RECV (state);
					break;
				case AIO_OP_SEND:
					state->total = ICALL_SEND (state);
					break;
				}
			}
#endif
			/* worker threads invokes methods in different domains,
			 * so we need to set the right domain here */
			g_assert (domain);

			if (mono_domain_is_unloading (domain) || mono_runtime_is_shutting_down ()) {
				threadpool_jobs_dec ((MonoObject *)ar);
				data = NULL;
				ar = NULL;
				InterlockedDecrement (&tp->busy_threads);
			} else {
				mono_thread_push_appdomain_ref (domain);
				if (threadpool_jobs_dec ((MonoObject *)ar)) {
					data = NULL;
					ar = NULL;
					mono_thread_pop_appdomain_ref ();
					InterlockedDecrement (&tp->busy_threads);
					continue;
				}

				if (mono_domain_set (domain, FALSE)) {
					MonoObject *exc;

					if (tp_item_begin_func)
						tp_item_begin_func (tp_item_user_data);

					exc = mono_async_invoke (tp, ar);
					if (tp_item_end_func)
						tp_item_end_func (tp_item_user_data);
					if (exc)
						mono_internal_thread_unhandled_exception (exc);
					if (is_socket && tp->is_io) {
						MonoSocketAsyncResult *state = (MonoSocketAsyncResult *) data;

						if (state->completed && state->callback) {
							MonoAsyncResult *cb_ares;
							cb_ares = create_simple_asyncresult ((MonoObject *) state->callback,
												(MonoObject *) state);
							icall_append_job ((MonoObject *) cb_ares);
						}
					}
					mono_domain_set (mono_get_root_domain (), TRUE);
				}
				mono_thread_pop_appdomain_ref ();
				InterlockedDecrement (&tp->busy_threads);
				clear_thread_state ();
			}
		}

		ar = NULL;
		data = NULL;
		must_die = should_i_die (tp);
		if (must_die) {
			mono_wsq_suspend (wsq);
		} else {
			if (tp->is_io || !mono_wsq_local_pop (&data))
				dequeue_or_steal (tp, &data, wsq);
		}

		n_naps = 0;
		while (!must_die && !data && n_naps < 4) {
			gboolean res;

			InterlockedIncrement (&tp->waiting);

			// Another thread may have added a job into its wsq since the last call to dequeue_or_steal
			// Check all the queues again before entering the wait loop
			dequeue_or_steal (tp, &data, wsq);
			if (data) {
				InterlockedDecrement (&tp->waiting);
				break;
			}

			mono_gc_set_skip_thread (TRUE);

#if defined(__OpenBSD__)
			while (mono_cq_count (tp->queue) == 0 && (res = mono_sem_wait (&tp->new_job, TRUE)) == -1) {// && errno == EINTR) {
#else
			while (mono_cq_count (tp->queue) == 0 && (res = mono_sem_timedwait (&tp->new_job, 2000, TRUE)) == -1) {// && errno == EINTR) {
#endif
				if (mono_runtime_is_shutting_down ())
					break;
				check_for_interruption_critical ();
			}
			InterlockedDecrement (&tp->waiting);

			mono_gc_set_skip_thread (FALSE);

			if (mono_runtime_is_shutting_down ())
				break;
			must_die = should_i_die (tp);
			dequeue_or_steal (tp, &data, wsq);
			n_naps++;
		}

		if (!data && !tp->is_io && !mono_runtime_is_shutting_down ()) {
			mono_wsq_local_pop (&data);
			if (data && must_die) {
				InterlockedCompareExchange (&tp->destroy_thread, 1, 0);
				pulse_on_new_job (tp);
			}
		}

		if (!data) {
			gint nt;
			gboolean down;
			while (1) {
				nt = tp->nthreads;
				down = mono_runtime_is_shutting_down ();
				if (!down && nt <= tp->min_threads)
					break;
				if (down || InterlockedCompareExchange (&tp->nthreads, nt - 1, nt) == nt) {
#ifndef DISABLE_PERFCOUNTERS
					mono_perfcounter_update_value (tp->pc_nthreads, TRUE, -1);
#endif
					if (!tp->is_io) {
						remove_wsq (wsq);
					}

					fire_profiler_thread_end ();

					if (tp_finish_func)
						tp_finish_func (tp_hooks_user_data);

					if (!tp->is_io) {
						if (threads) {
							mono_mutex_lock (&threads_lock);
							if (threads)
								g_ptr_array_remove_fast (threads, mono_thread_current ()->internal_thread);
							mono_mutex_unlock (&threads_lock);
						}
					}

					return;
				}
			}
		}
	}

	g_assert_not_reached ();
}

void
ves_icall_System_Threading_ThreadPool_GetAvailableThreads (gint *workerThreads, gint *completionPortThreads)
{
	*workerThreads = async_tp.max_threads - async_tp.busy_threads;
	*completionPortThreads = async_io_tp.max_threads - async_io_tp.busy_threads;
}
Example #29
0
/* Build a menu of the given bookmarks categorised by the given topics.
 * Shows categorisation using subdivisions, submenus, or a mix of both. */
static void
append_menu (GString *string, const GPtrArray *topics, const GPtrArray *bookmarks, guint flags)
{
	GPtrArray *uncovered;
	guint i, j;
	
	gboolean use_subdivis = flags & BUILD_SUBDIVIS;
	gboolean use_submenus = flags & BUILD_SUBMENUS;        

	if (use_subdivis || use_submenus)
	{
		GPtrArray *subset, *covering, *subdivisions, *submenus, *unused;
		GArray *sizes = 0;
		EphyNode *topic;
		gint size, total;
		gboolean separate = FALSE;
		char name[EPHY_TOPIC_ACTION_NAME_BUFFER_SIZE];
		
		/* Get the subtopics, uncovered bookmarks, and subtopic sizes. */
		sizes = g_array_sized_new (FALSE, FALSE, sizeof(int), topics->len);
		uncovered = g_ptr_array_sized_new (bookmarks->len);
		covering = ephy_nodes_get_covering (topics, bookmarks, 0, uncovered, sizes);

		/* Preallocate arrays for submenus, subdivisions, and bookmark subsets. */
		subdivisions = g_ptr_array_sized_new (topics->len);
		submenus = g_ptr_array_sized_new (topics->len);
		subset = g_ptr_array_sized_new (bookmarks->len);
		unused = g_ptr_array_sized_new (bookmarks->len);

		/* Get the total number of items in the menu. */
		total = uncovered->len;
		for (i = 0; i < covering->len; i++)
		  total += g_array_index (sizes, int, i);
		
		/* Seperate covering into list of submenus and subdivisions */
		for (i = 0; i < covering->len; i++)
		{
			topic = g_ptr_array_index (covering, i);
			size = g_array_index (sizes, int, i);
			
			if (!use_submenus || (use_subdivis && (size < MIN_MENU_SIZE || total < MAX_MENU_SIZE)))
			{
				g_ptr_array_add (subdivisions, topic);
			}
			else
			{
				g_ptr_array_add (submenus, topic);
				total = total - size + 1;
			}
		}
		
		/* Sort the list of submenus and subdivisions. */
		g_ptr_array_sort (submenus, ephy_bookmarks_compare_topic_pointers);
		g_ptr_array_sort (subdivisions, ephy_bookmarks_compare_topic_pointers);
		
		if (flags & BUILD_CHILD_SUBDIVIS) flags |= BUILD_SUBDIVIS;
		if (flags & BUILD_CHILD_SUBMENUS) flags |= BUILD_SUBMENUS;
		
		/* Create each of the submenus. */
		for (i = 0; i < submenus->len; i++)
		{
			topic = g_ptr_array_index (submenus, i);
			ephy_nodes_get_covered (topic, bookmarks, subset);

			EPHY_TOPIC_ACTION_NAME_PRINTF (name, topic);
				
			g_string_append_printf (string, "<menu action=\"%s\">",
						name);
			append_menu (string, topics, subset, flags);
			g_string_append (string, "</menu>");
			separate = TRUE;
		}
		
		/* Build a list of bookmarks which don't appear in any subdivision yet. */
		for (i = 0; i < bookmarks->len; i++)
		{
			g_ptr_array_add (unused, g_ptr_array_index (bookmarks, i));
		}

		/* Create each of the subdivisions. */
		for (i = 0; i < subdivisions->len; i++)
		{
			topic = g_ptr_array_index (subdivisions, i);
			ephy_nodes_get_covered (topic, unused, subset);
			g_ptr_array_sort (subset, ephy_bookmarks_compare_bookmark_pointers);
			
			if (separate) g_string_append (string, "<separator/>");
			append_bookmarks (string, subset);
			separate = TRUE;
			
			/* Record that each bookmark has been added. */
			for (j = 0; j < subset->len; j++)
			{
				g_ptr_array_remove_fast (unused, g_ptr_array_index (subset, j));
			}
		}

		g_array_free (sizes, TRUE);
		g_ptr_array_free (covering, TRUE);
		g_ptr_array_free (subdivisions, TRUE);
		g_ptr_array_free (submenus, TRUE);
		g_ptr_array_free (subset, TRUE);
		g_ptr_array_free (unused, TRUE);
		
		if (separate && uncovered->len) g_string_append (string, "<separator/>");
	}
Example #30
0
/******************************************************************
 * This function is called when an event occurs on a client socket
 ******************************************************************/
void client_cb(int fd, short events, void *arg)
{
    assert(arg != NULL);

    Client *cli = arg;
    int free = 0;

    // g_hash_table_foreach(g_jobqueue, _print_queue, NULL);

    if ((events & EV_WRITE) != 0) {
        event_del(&cli->evt);
        cli->evt.ev_events = EV_READ|EV_PERSIST;
        event_add(&cli->evt, NULL);
        if (client_flush(cli) < 0) {
            free = 1;
        }
    }
    if ((events & EV_READ) != 0) {
        int ret = 0;
        if (!cli->buffer_in) {
            cli->buffer_in = getBlock(HEADER_SIZE);
            incRef(cli->buffer_in);
            ret = client_recv(cli, HEADER_SIZE);
        }
        if (ret >= 0) {
            /* Make sure we don't over-read into the next packet */
            int psize = HEADER_SIZE;
            if (cli->buffer_in->nbytes >= HEADER_SIZE) {
                if (ntohl(*(uint32_t*)(cli->buffer_in->bytes + HEADER_OFFSET_MAGIC)) != MAGIC_REQUEST) {
                    free = 1;
                    g_warning("[%s] Invalid MAGIC", cli->id);
                    goto free_client;
                }
                psize = HEADER_SIZE + ntohl(*(uint32_t*)(cli->buffer_in->bytes + HEADER_OFFSET_SIZE));
                /* If the input block isn't large enough to receive the
                   entire packet then switch to one that is */
                if (psize > cli->buffer_in->size) {
                    #if DEBUG
                    g_debug("Switching to bigger block (pktsize=%d)", psize);
                    #endif

                    /* Create new (bigger) block */
                    MemBlock *block = getBlock(psize + 1); /* +1 for terminating NULL to make args easier to work with */
					if (!block) {
                        g_error("Failed to get block of size %d", psize);
						free = 1;
						goto free_client;
					}
                    incRef(block);

                    /* Copy bytes into new block */
                    block->nbytes = cli->buffer_in->nbytes;
                    memmove(block->bytes, cli->buffer_in->bytes, cli->buffer_in->nbytes);

                    /* Swap blocks */
                    decRef(cli->buffer_in);
                    cli->buffer_in = block;
                }
            }
            int num = psize - cli->buffer_in->nbytes;
            if (num > 0)
                ret = client_recv(cli, num);
        }
        if (ret < 0) {
            #if DEBUG
            g_debug("[%s] Connection on closed", cli->id);
            #endif
            free = 1;
        } else if (ret >= 0) {
            if (process_client(cli) != 0) {
                g_warning("[%s] Processing of client failed", cli->id);
                free = 1;
            }
        }
    }
    /*if ((events & (EV_READ|EV_WRITE)) == 0) {
        g_warning("[%s] unhandled event %d", __func__, events);
    }*/

free_client:
    if (free != 0) {
        #if DEBUG
        g_message("[%s] Client disconnected", cli->id);
        #endif

        /*printf("[%s] Removing client %d\n", __func__, cli->fd);*/
        close(cli->fd);
        cli->fd = -1;

        fail_working_jobs(cli);
        stop_all_listening(cli);
        unregister_all_abilities(cli);

        event_del(&cli->evt);
        g_ptr_array_remove_fast(g_clients, cli);

        client_free(cli);
    }
}