Ejemplo n.º 1
0
gboolean is_expired_client(gpointer key,
			   gpointer value, gpointer user_data)
{
	gboolean ret = FALSE;
	if (! value) {
		return FALSE;
	}
	if (((user_session_t *) value)->expire == -1) {
		return FALSE;
	}
	if (((user_session_t *) value)->expire < *((time_t *) user_data)) {
		if (g_mutex_trylock(((user_session_t *) value)->rw_lock)) {
			ret = TRUE;
			g_mutex_unlock(((user_session_t *) value)->rw_lock);
		} else {
			((user_session_t *) value)->pending_disconnect = TRUE;
		}
	}
	/* If no USER_HELLO is received for some time, client deserve death */
	if (*((time_t *) user_data) - ((user_session_t *) value)->last_request
			> NU_USER_HELLO_INTERVAL + NU_USER_HELLO_GRACETIME) {
		if (g_mutex_trylock(((user_session_t *) value)->rw_lock)) {
			ret = TRUE;
			g_mutex_unlock(((user_session_t *) value)->rw_lock);
		} else {
			((user_session_t *) value)->pending_disconnect = TRUE;
		}
	}
	return ret;
}
Ejemplo n.º 2
0
int wait_for_cb(cb_ctx_t *cb_ctx, void **ret_pointer, GError **gerr)
{
    int wait_cnt = 0;
    if (!g_mutex_trylock(&cb_ctx->pending_cb_mtx) &&
        is_event_loop_running()) {
        // Reset return value
        cb_ctx->cb_ret_val     = BL_NO_CALLBACK_ERROR;
        cb_ctx->cb_ret_pointer = NULL;

        printf_dbg("Waiting for callback\n");
        while (is_event_loop_running() &&
               !g_mutex_trylock(&cb_ctx->pending_cb_mtx)) {
            usleep(100000);

            if (wait_cnt < CB_TIMEOUT_S*10) {
                wait_cnt++;
            } else {
                GError *err = g_error_new(BL_ERROR_DOMAIN,
                                          BL_NO_CALLBACK_ERROR,
                                          "Timeout no callback received\n");
                printf_dbg("%s", err->message);
                PROPAGATE_ERROR;
                set_conn_state(cb_ctx->dev_ctx, STATE_DISCONNECTED);
                return BL_NO_CALLBACK_ERROR;
            }
        }
    }

    if (!is_event_loop_running()) {
        set_conn_state(cb_ctx->dev_ctx, STATE_DISCONNECTED);
        GError *err = g_error_new(BL_ERROR_DOMAIN, BL_DISCONNECTED_ERROR,
                                  "Event loop is not running\n");
        printf_dbg("%s", err->message);
        PROPAGATE_ERROR;
        return BL_DISCONNECTED_ERROR;
    } else
        printf_dbg("Callback returned <%d, %p>\n", cb_ctx->cb_ret_val,
                   cb_ctx->cb_ret_pointer);

    if (cb_ctx->cb_ret_val != BL_NO_ERROR) {
        GError *err = g_error_new(BL_ERROR_DOMAIN, cb_ctx->cb_ret_val, "%s",
                                  cb_ctx->cb_ret_msg);
        PROPAGATE_ERROR;
    }

    if (*cb_ctx->cb_ret_msg != '\0') {
        printf_dbg("%s", cb_ctx->cb_ret_msg);
    }
    strcpy(cb_ctx->cb_ret_msg, "\0");
    if (ret_pointer)
        *ret_pointer = cb_ctx->cb_ret_pointer;
    return cb_ctx->cb_ret_val;
}
Ejemplo n.º 3
0
Archivo: gdk.c Proyecto: 3v1n0/gtk
static void
gdk_threads_impl_unlock (void)
{
  /* we need a trylock() here because trying to unlock a mutex
   * that hasn't been locked yet is:
   *
   *  a) not portable
   *  b) fail on GLib ≥ 2.41
   *
   * trylock() will either succeed because nothing is holding the
   * GDK mutex, and will be unlocked right afterwards; or it's
   * going to fail because the mutex is locked already, in which
   * case we unlock it as expected.
   *
   * this is needed in the case somebody called gdk_threads_init()
   * without calling gdk_threads_enter() before calling gtk_main().
   * in theory, we could just say that this is undefined behaviour,
   * but our documentation has always been *less* than explicit as
   * to what the behaviour should actually be.
   *
   * see bug: https://bugzilla.gnome.org/show_bug.cgi?id=735428
   */
  g_mutex_trylock (&gdk_threads_mutex);
  g_mutex_unlock (&gdk_threads_mutex);
}
Ejemplo n.º 4
0
static gboolean
anjuta_async_command_notification_poll (AnjutaCommand *command)
{
	AnjutaAsyncCommand *self;
	
	self = ANJUTA_ASYNC_COMMAND (command);
	
	if (self->priv->new_data_arrived &&
		g_mutex_trylock (&self->priv->mutex))
	{
		g_signal_emit_by_name (command, "data-arrived");
		g_mutex_unlock (&self->priv->mutex);
		self->priv->new_data_arrived = FALSE;
	}
	
	if (self->priv->progress_changed)
	{
		g_signal_emit_by_name (command, "progress", self->priv->progress);
		self->priv->progress_changed = FALSE;
	}
	
	if (self->priv->complete)
	{
		g_signal_emit_by_name (command, "command-finished", 
							   self->priv->return_code);
		return FALSE;
	}
	else
		return TRUE;
	
}
Ejemplo n.º 5
0
gpointer timer_thread(gpointer data)
{

    struct start_drakvuf* start = (struct start_drakvuf*)data;

    gboolean gotlock = FALSE;

    while (start->timer > 0)
    {
        gotlock = g_mutex_trylock(&start->timer_lock);
        if ( gotlock )
        {
            g_mutex_unlock(&start->timer_lock);
            break;
        }

        start->timer--;
        sleep(1);
    }

    if ( !gotlock )
        cleanup(start->cloneID, start->threadid+1);

    return NULL;
}
Ejemplo n.º 6
0
/* Thread function to check that a mutex given in @data is locked */
static gpointer
mutex_locked_thread (gpointer data)
{
  GMutex *mutex = (GMutex *) data;
  g_assert_false (g_mutex_trylock (mutex));
  return NULL;
}
Ejemplo n.º 7
0
/**
 * oh_wake_event_thread
 * @wait: Says whether we should wait for the event thread
 * to do one round through the plugin instances. Otherwise, we
 * just knock on the event thread's door and return quickly.
 *
 * If wait is true, the event thread is woken up
 * and we wait until it does a round throughout the
 * plugin instances. If the thread is already running,
 * we will wait for it until it completes the round.
 *
 * Returns: void
 **/
void oh_wake_event_thread(SaHpiBoolT wait)
{
        if (!wait) { /* If not waiting, just signal the thread and go. */
                g_cond_broadcast(oh_event_thread_wait);
                return;
        }

        g_static_mutex_lock(&oh_wake_event_mutex);
        if (g_mutex_trylock(oh_event_thread_mutex)) {
                /* The thread was asleep; wake it up. */
                trace("Going to wait for event thread to loop once.");
                g_cond_broadcast(oh_event_thread_wait);
                g_cond_wait(oh_event_thread_wait,
                            oh_event_thread_mutex);
                trace("Got signal from event"
                        " thread being done. Giving lock back");
                g_mutex_unlock(oh_event_thread_mutex);
        } else {
                /* Thread was already up. Wait until it completes */
                trace("Waiting for event thread...");
                g_mutex_lock(oh_event_thread_mutex);
                trace("...Done waiting for event thread.");
                g_mutex_unlock(oh_event_thread_mutex);
        }
        g_static_mutex_unlock(&oh_wake_event_mutex);

        return;
}
/*
 * The timer-based process that operates on some variables then invalidates drawingarea1's region to trigger
 * an expose_event, thus invoking function "on_drawingarea1_expose_event" through the window manager.
 *
 */
gboolean SludgeGLApplication::render_timer_event(gpointer theUser_data)
{
	GtkWidget *theWidget = GTK_WIDGET (theUser_data);

	/*
	 * Only send a redraw request if the render process is not busy.  This prevents long rendering processes
	 * from piling up.
	 */
	if (g_mutex_trylock(theRender_mutex))
	{
		// Unlock the mutex before we issue the redraw.
		g_mutex_unlock(theRender_mutex);
		// Invalidate drawingarea1's region to signal the window handler there needs to be an update in that area,
		gdk_window_invalidate_rect (gtk_widget_get_parent_window (theWidget), &theWidget->allocation, TRUE);
//		gdk_window_invalidate_rect (theWidget->window, &theWidget->allocation, FALSE);
		/*
		 * Force an immediate update - we can omit this and leave the window manager to call the redraw when the
		 * main loop is idle.  However, we get smoother, more consistent updates this way.
		 */
		gdk_window_process_updates (gtk_widget_get_parent_window (theWidget), TRUE);
//		gdk_window_process_updates (theWidget->window, FALSE);
	}

	return TRUE;
}
Ejemplo n.º 9
0
/*
 *   This method is unreliable, and for use
 * only for debugging.
 */
gboolean
link_mutex_is_locked (GMutex *lock)
{
#ifdef __GLIBC__
	gboolean result = TRUE;

	if (lock && g_mutex_trylock (lock)) {
		result = FALSE;
		g_mutex_unlock (lock);
	}

	return result;
#else
	/*
	 * On at least Solaris & BSD if we link our
	 * app without -lthread, and pull in ORBit2
	 * with threading enabled, we get NOP pthread
	 * operations. This is fine mostly, but we get
	 * bogus return values from trylock which screws
	 * our debugging.
	 */
	d_printf ("hosed system is_lock-ing\n");
	return TRUE;
#endif
}
Ejemplo n.º 10
0
void
gkd_gpg_agent_uninitialize (void)
{
	gboolean ret;

	g_assert (pkcs11_main_mutex);
	ret = g_mutex_trylock (pkcs11_main_mutex);
	g_assert (ret);

		g_assert (GCK_IS_SESSION (pkcs11_main_session));
		g_assert (!pkcs11_main_checked);
		g_object_unref (pkcs11_main_session);
		pkcs11_main_session = NULL;

	g_mutex_unlock (pkcs11_main_mutex);
	g_mutex_free (pkcs11_main_mutex);
	g_cond_free (pkcs11_main_cond);

	g_assert (pkcs11_module);
	g_object_unref (pkcs11_module);
	pkcs11_module = NULL;

	g_assert (cache_settings);
	g_object_unref (cache_settings);
	cache_settings = NULL;
}
Ejemplo n.º 11
0
static void
trylock_locked_mutex (void)
{
  GMutex* mutex = g_mutex_new ();
  g_mutex_lock (mutex);
  g_mutex_trylock (mutex);
}
Ejemplo n.º 12
0
void gldi_task_discard (GldiTask *pTask)
{
	if (pTask == NULL)
		return ;
	
	_cancel_next_iteration (pTask);
	// mark the task as 'discarded'
	g_atomic_int_set (&pTask->bDiscard, 1);
	
	// if the task is running, there is nothing to do:
	//   if we're inside the thread, it will trigger the 'update' anyway, which will destroy the task.
	//   if we're waiting for the 'update', same as above
	//   if we're inside the 'update' user callback, the task will be destroyed in the 2nd stage of the function (the user callback is called in the 1st stage).
	if (! gldi_task_is_running (pTask))  // we can free the task immediately.
	{
		if (pTask->pThread && pTask->pCond && g_mutex_trylock (pTask->pMutex))  // the thread is sleeping, awake it and let it exit before we can free everything
		{
			pTask->bRunThread = TRUE;
			g_cond_signal (pTask->pCond);
			g_mutex_unlock (pTask->pMutex);
			g_thread_join (pTask->pThread);  // unref the thread
			pTask->pThread = NULL;
		}
		_free_task (pTask);
	}
}
Ejemplo n.º 13
0
void user_worker(gpointer psession, gpointer data)
{
    user_session_t *usersession = (user_session_t *) psession;
    struct msg_addr_set *gmsg;
    int ret;
    gboolean sess_ok = TRUE;


    if (g_mutex_trylock(usersession->rw_lock)) {
        while (sess_ok && (gmsg = g_async_queue_try_pop(usersession->workunits_queue))) {
            if (gmsg == GINT_TO_POINTER(0x1)) {
                debug_log_message(VERBOSE_DEBUG, DEBUG_AREA_USER,
                                  "reading message from \"%s\"",
                                  usersession->user_name);
                ret = tls_user_check_activity(usersession);
                switch (ret) {
                case NU_EXIT_OK:
                case NU_EXIT_CONTINUE:
                    break;
                case NU_EXIT_ERROR:
                    log_message(INFO, DEBUG_AREA_USER,
                                "Problem reading message from \"%s\"",
                                usersession->user_name);
                    usersession->pending_disconnect = TRUE;
                    sess_ok = FALSE;
                    break;
                }
            } else {
                debug_log_message(VERBOSE_DEBUG, DEBUG_AREA_USER,
                                  "writing message to \"%s\"",
                                  usersession->user_name);

                /* send message */
                ret = nussl_write(usersession->nussl,
                                  (char*)gmsg->msg,
                                  ntohs(gmsg->msg->length));
                g_free(gmsg->msg);
                g_free(gmsg);
                if (ret < 0) {
                    debug_log_message(VERBOSE_DEBUG, DEBUG_AREA_USER,
                                      "client disconnect");
                    usersession->pending_disconnect = TRUE;
                    sess_ok = FALSE;
                    break;
                }
            }
        }
        /* send socket back to user select no message are waiting */
        g_async_queue_push(mx_queue, usersession);
        g_mutex_unlock(usersession->rw_lock);
        ev_async_send(usersession->srv_context->loop,
                      &usersession->srv_context->client_injector_signal);

    } else {
        debug_log_message(VERBOSE_DEBUG, DEBUG_AREA_USER,
                          "client locked at %s:%d", __FILE__, __LINE__);

    }
    return;
}
Ejemplo n.º 14
0
void
rb_threads_init (void)
{
	GMutex *m;

	private_is_primary_thread = g_private_new (NULL);
	g_private_set (private_is_primary_thread, GUINT_TO_POINTER (1));

	g_static_rec_mutex_init (&rb_gdk_mutex);
	gdk_threads_set_lock_functions (_threads_enter, _threads_leave);
	gdk_threads_init ();

	m = g_mutex_new ();

	g_mutex_lock (m);
	mutex_recurses = g_mutex_trylock (m);
	if (mutex_recurses)
		g_mutex_unlock (m);
	g_mutex_unlock (m);
	g_mutex_free (m);

	rb_debug ("GMutex %s recursive", mutex_recurses ? "is" : "isn't");

	/* purge useless thread-pool threads occasionally */
	g_timeout_add_seconds (30, purge_useless_threads, NULL);
}
Ejemplo n.º 15
0
/* ---------------------------
 * GVA_fcache_mutex_trylock
 * ---------------------------
 * lock the fcache_mutex if present (i.e. is NOT NULL)
 * return immediate FALSE in case the mutex is locked by another thread
 * return TRUE in case the mutex was locked successfully (may sleep until other threads unlock the mutex)
 *        TRUE will be immediatly returned in case
 *        a) thread system is not initialized, i.e g_thread_init was not yet called
 *        b) in case the gvahand->fcache_mutex is NULL (which is default after opening a videohandle)
 */
gboolean
GVA_fcache_mutex_trylock(t_GVA_Handle  *gvahand)
{
  gboolean isSuccessful;

  if(gvahand->fcache_mutex)
  {
    GAP_TIMM_START_RECORD(&gvahand->fcacheMutexLockStats);

    isSuccessful = g_mutex_trylock (gvahand->fcache_mutex);

    GAP_TIMM_STOP_RECORD(&gvahand->fcacheMutexLockStats);
  }
  else
  {
    /* not really locked, because no mutex is available.
     * but in this case behave same as g_mutex_trylock
     * when thread system is not initialized, i.e g_thread_init was not yet called
     */
    isSuccessful = TRUE;
  }

  return(isSuccessful);
  
}  /* end GVA_fcache_mutex_trylock */
Ejemplo n.º 16
0
/*
 * execute client destruction task
 */
static void client_destructor_cb(struct ev_loop *loop, ev_async *w, int revents)
{
    struct tls_user_context_t *context = (struct tls_user_context_t *) w->data;
    disconnect_user_msg_t *disconnect_msg;
    user_session_t *session;

    disconnect_msg = g_async_queue_pop(context->cmd_queue);

    if (disconnect_msg->socket == -1) {
        disconnect_msg->result = kill_all_clients();
    } else {
        session = get_client_datas_by_socket(disconnect_msg->socket);
        if (session == NULL) {
            g_mutex_lock(disconnect_msg->mutex);
            disconnect_msg->result = NU_EXIT_ERROR;
            g_cond_signal(disconnect_msg->cond);
            g_mutex_unlock(disconnect_msg->mutex);
            unlock_client_datas();
            return;
        }
        if (g_mutex_trylock(session->rw_lock)) {
            ev_io_stop(session->srv_context->loop,
                       &session->client_watcher);
            disconnect_msg->result = delete_rw_locked_client(session);
        } else {
            session->pending_disconnect = TRUE;
            disconnect_msg->result = NU_EXIT_OK;
        }
        unlock_client_datas();
    }
    g_mutex_lock(disconnect_msg->mutex);
    g_cond_signal(disconnect_msg->cond);
    g_mutex_unlock(disconnect_msg->mutex);
}
Ejemplo n.º 17
0
static void __client_writer_cb(struct ev_loop *loop, struct tls_user_context_t *context, int revents)
{
    user_session_t *session;
    int fd;
#if DEBUG_ENABLE
    int i = 0;
#endif
    while ((fd = GPOINTER_TO_INT(g_async_queue_try_pop(writer_queue)))) {
        session = get_client_datas_by_socket(fd);
        if (session == NULL) {
            continue;
        }
        if (g_mutex_trylock(session->rw_lock)) {
            ev_io_stop(session->srv_context->loop,
                       &session->client_watcher);
            debug_log_message(VERBOSE_DEBUG, DEBUG_AREA_USER,
                              "sending session to user_workers (%d)",
                              i);
            g_mutex_unlock(session->rw_lock);
            thread_pool_push(nuauthdatas->user_workers, session, NULL);
        }
#if DEBUG_ENABLE
        i++;
#endif
        unlock_client_datas();
    }
}
Ejemplo n.º 18
0
void gldi_task_stop (GldiTask *pTask)
{
	if (pTask == NULL)
		return ;
	
	_cancel_next_iteration (pTask);
	
	if (gldi_task_is_running (pTask))
	{
		if (pTask->pThread)
		{
			g_atomic_int_set (&pTask->bDiscard, 1);  // set the discard flag to help the 'get_data' callback knows that it should stop.
			if (pTask->pCond)  // the thread might be sleeping, awake it.
			{
				if (g_mutex_trylock (pTask->pMutex))
				{
					pTask->bRunThread = TRUE;
					g_cond_signal (pTask->pCond);
					g_mutex_unlock (pTask->pMutex);
				}
			}
			g_thread_join (pTask->pThread);  // unref the thread
			pTask->pThread = NULL;
			g_atomic_int_set (&pTask->bDiscard, 0);
		}
		if (pTask->iSidUpdateIdle != 0)  // do it after the thread has possibly scheduled the 'update'
		{
			g_source_remove (pTask->iSidUpdateIdle);
			pTask->iSidUpdateIdle = 0;
		}
		pTask->bIsRunning = FALSE;  // since we didn't go through the 'update'
	}
	else
	{
		if (pTask->pThread && pTask->pCond && g_mutex_trylock (pTask->pMutex))  // the thread is sleeping, awake it and let it exit.
		{
			g_atomic_int_set (&pTask->bDiscard, 1);
			pTask->bRunThread = TRUE;
			g_cond_signal (pTask->pCond);
			g_mutex_unlock (pTask->pMutex);
			g_thread_join (pTask->pThread);  // unref the thread
			pTask->pThread = NULL;
			g_atomic_int_set (&pTask->bDiscard, 0);
		}
	}
}
Ejemplo n.º 19
0
/**
 * Decrease reference count of a blob system; destroy it if the count reaches zero.
 *
 * @param[in] self the blob system object
 *
 * This function decreases the reference count of the blob system
 * object given. If the reference count reaches zero, the blob system
 * will be destroyed. If there were pending requests in a to-be-destroyed
 * blob system, this fact will be logged.
 **/
void
z_blob_system_unref(ZBlobSystem *self)
{
  ZBlob *blob;
  GList *cur, *next;
  gint n;

  z_enter();
  g_assert(self); 
  if (z_refcount_dec(&self->ref_cnt))
    {
      self->active = FALSE;
      /** @todo FIXME: itt lockolni kell */
      g_async_queue_push(self->req_queue, Z_BLOB_THREAD_KILL);
      g_thread_join(self->thr_management);

      n = 0;
      for (cur = self->waiting_list; cur; cur = next)
        {
          next = cur->next;
          blob = (ZBlob*) cur->data;
          blob->approved = FALSE;
          z_blob_signal_ready(blob);
          self->waiting_list = g_list_delete_link(self->waiting_list, cur);
          n++;
        }
      if (n)
        z_log(NULL, CORE_INFO, 5, "Pending requests found for a to-be-destroyed blob system; num_requests='%d'", n);

      n = 0;
      for (cur = self->blobs; cur; cur = next)
        {
          next = cur->next;
          blob = (ZBlob*)cur->data;
          z_blob_unref(blob);
          n++;
        }
      if (n)
        z_log(NULL, CORE_INFO, 5, "Active blobs found in a to-be-destroyed blob system; num_blobs='%d'", n);

      if (self->dir)
        g_free(self->dir);
      if (g_mutex_trylock(self->mtx_blobsys))
        {
          g_mutex_unlock(self->mtx_blobsys);
          g_mutex_free(self->mtx_blobsys);
        }
      else
        {
          /* Some blob operations are in progress: z_blob_new, _unref, _alloc, _get_file */
        }
      g_cond_free(self->cond_thread_started);
      g_async_queue_unref(self->req_queue);
      g_list_free(self->waiting_list);
      g_free(self);
    }
  z_return();
}
Ejemplo n.º 20
0
static inline int find_thread()
{
    unsigned int i=0;
    for (;i<threads;i++) {
        if(g_mutex_trylock(&locks[i]))
            return i;
    }
    return -1;
}
Ejemplo n.º 21
0
/**
 * Lock a blob.
 *
 * @param[in] self this
 * @param[in] timeout Timeout for locking. A negative value means infinite and thus blocking mode. Zero means nonblocking mode.
 *
 * @returns TRUE if successfully locked.
 **/
gboolean
z_blob_lock(ZBlob *self, gint timeout)
{
  gboolean        res;
  struct timeval  tvnow, tvfinish;

  z_enter();
  g_assert(self);

  if (timeout < 0)        /* infinite timeout -> blocking mode */
    {
      g_mutex_lock(self->mtx_lock);
      res = TRUE;
    }
  else if (timeout == 0)  /* zero timeout -> nonblocking mode */
    {
      res = g_mutex_trylock(self->mtx_lock);
    }
  else                    /* positive timeout */
    {
      gettimeofday(&tvfinish, NULL);
      tvfinish.tv_sec += (timeout / 1000);
      tvfinish.tv_usec += 1000 * (timeout % 1000);
      tvfinish.tv_sec += (tvfinish.tv_usec / 1000000);
      tvfinish.tv_usec %= 1000000;
      /* FIXME: maybe g_cond_wait_timed_wait ? */
      do
        {
          res = FALSE;
          if (g_mutex_trylock(self->mtx_lock))
            {
              res = TRUE;
              break;
            }
          usleep(1000);
          gettimeofday(&tvnow, NULL);
        } 
      while ((tvnow.tv_sec < tvfinish.tv_sec) ||
             ((tvnow.tv_sec == tvfinish.tv_sec) && (tvnow.tv_usec < tvfinish.tv_usec)));
    }
  z_return(res);
}
Ejemplo n.º 22
0
static gpointer
test_g_mutex_thread (gpointer data)
{
  g_assert (GPOINTER_TO_INT (data) == 42);
  g_assert (g_mutex_trylock (&test_g_mutex_mutex) == FALSE);
  g_assert (G_TRYLOCK (test_g_mutex) == FALSE);
  test_g_mutex_thread_ready = TRUE;
  g_mutex_lock (&test_g_mutex_mutex);
  g_assert (test_g_mutex_int == 42);
  g_mutex_unlock (&test_g_mutex_mutex);

  return GINT_TO_POINTER (41);
}
Ejemplo n.º 23
0
void client_activity_cb(struct ev_loop *loop, ev_io *w, int revents)
{
    struct tls_user_context_t *context = (struct tls_user_context_t *) w->data;
    /* get_client_datas_by_socket acquire client datas lock if session is found */
    user_session_t *c_session = get_client_datas_by_socket(w->fd);

    if (! c_session) {
        log_message(WARNING, DEBUG_AREA_USER,
                    "Unable to find session for %d", w->fd);
        return;
    }

    debug_log_message(VERBOSE_DEBUG, DEBUG_AREA_USER,
                      "User activity for \"%s\" (in cb)",
                      c_session->user_name);

    if (c_session->activated) {
        c_session->activated = FALSE;
    }

    ev_io_stop(context->loop, w);

    if (revents & EV_ERROR) {
        log_message(INFO, DEBUG_AREA_USER,
                    "Error on socket %d", w->fd);
        delete_locked_client_by_socket(w->fd);
        unlock_client_datas();
        return;
    }
    if (revents & EV_READ) {
        debug_log_message(VERBOSE_DEBUG, DEBUG_AREA_USER,
                          "Reading needed for user \"%s\"(in cb)",
                          c_session->user_name);
        g_async_queue_push(c_session->workunits_queue, GINT_TO_POINTER(0x1));
        thread_pool_push(nuauthdatas->user_workers, c_session, NULL);
        unlock_client_datas();
        return;
    }
    /* we should not reach this point */
    log_message(WARNING, DEBUG_AREA_USER, "Surprising event from libev: %d",
                revents);
    /* disconnecting session to be sure */
    if (g_mutex_trylock(c_session->rw_lock)) {
        delete_rw_locked_client(c_session);
    } else {
        c_session->pending_disconnect = TRUE;
    }
    unlock_client_datas();
}
Ejemplo n.º 24
0
static gboolean _maybe_remove_servlet(gpointer key, gpointer value, gpointer user_data)
{
  xr_servlet* servlet = value;
  xr_server* server = user_data;

  if (g_mutex_trylock(servlet->call_mutex))
  {
    g_mutex_unlock(servlet->call_mutex); /* this is ok, as nobody else is going to take this lock during remove */
    gboolean remove = (servlet->last_used + 60 < server->current_time || servlet->last_used > server->current_time);
    return remove;
  }

  /* servlet is locked, can't remove */
  return FALSE;
}
Ejemplo n.º 25
0
/************************************************************************
 * The following procedure is the callback for angular change button
 * presses.
 ************************************************************************/
void angleAdjustmentButtonPressed(GtkWidget *widget, struct AngleAdjustment *angleAdjustment) {
    gint getval;

    if (g_mutex_trylock(angleAdjustment->context->atEnd) == TRUE) {
        getval = 1;
        g_mutex_unlock(angleAdjustment->context->atEnd);
    } else
        getval = 0;

    angleAdjustment->context->iangle = angleAdjustment->idelta;
    angleAdjustment->context->jangle = angleAdjustment->jdelta;
    angleAdjustment->context->kangle = angleAdjustment->kdelta;
    if (angleAdjustment->context->pausecheck || getval == 0)
        triggerImageRedraw(widget, angleAdjustment->context);
}
Ejemplo n.º 26
0
void mouseRotate(GtkWidget *widget, gint xdelta, gint ydelta,
                 struct Context *context) {
    gint getval;

    if (g_mutex_trylock(context->atEnd) == TRUE) {
        getval = 1;
        g_mutex_unlock(context->atEnd);
    } else
        getval = 0;

    context->imangle = (xdelta * 90.0) / (double) context->config->absxsize;
    context->jmangle = (ydelta * 90.0) / (double) context->config->absysize;
    if (context->pausecheck || context->config->waitForNextFramePress || getval == 0)
        triggerImageRedraw(widget, context);
}
Ejemplo n.º 27
0
/* Check handles periodically; shut down inactive ones, and send NOOP to
 * host to keep active connections alive. */
static void
lb_imap_server_cleanup(LibBalsaImapServer * imap_server)
{
    time_t idle_marker;
    GList *list;

    /* Quit if there is an action going on, eg. an connection is being
     * opened and the user is asked to confirm the certificate or
     * provide password, etc. */
    if(!g_mutex_trylock(&imap_server->lock))
        return; 

    idle_marker = time(NULL) - CONNECTION_CLEANUP_IDLE_TIME;

    list = imap_server->free_handles;
    while (list) {
        GList *next = list->next;
        struct handle_info *info = list->data;

        if (info->last_used < idle_marker) {
            imap_server->free_handles =
                g_list_delete_link(imap_server->free_handles, list);
            lb_imap_server_info_free(info);
        }

        list = next;
    }

    idle_marker -=
        CONNECTION_CLEANUP_NOOP_TIME - CONNECTION_CLEANUP_IDLE_TIME;

    for (list = imap_server->used_handles; list; list = list->next) {
        struct handle_info *info = list->data;
        /* We poll selected handles each time (unless IDLE is on
           already).  Remaining handles are just kept alive. */ 
        if ( (imap_mbox_is_selected(info->handle) &&
              !imap_server->use_idle) || 
            info->last_used < idle_marker) {
            /* ignore errors here - the point is to keep the
               connection alive and if there is no connection, noop
               will be, well, no-op. Other operations may possibly
               reconnect. */
            imap_mbox_handle_noop(info->handle);
        }
    }

    g_mutex_unlock(&imap_server->lock);
}
Ejemplo n.º 28
0
void gldi_task_launch (GldiTask *pTask)
{
	g_return_if_fail (pTask != NULL);
	if (pTask->get_data == NULL)  // no asynchronous work -> just call the 'update' and directly schedule the next iteration
	{
		_set_elapsed_time (pTask);
		pTask->bContinue = pTask->update (pTask->pSharedMemory);
		if (! pTask->bContinue)
		{
			_cancel_next_iteration (pTask);
		}
		else
		{
			pTask->iFrequencyState = GLDI_TASK_FREQUENCY_NORMAL;
			_schedule_next_iteration (pTask);
		}
	}
	else  // launch the asynchronous work in a thread
	{
		if (pTask->pThread == NULL)  // no thread yet -> create and launch it
		{
			pTask->bIsRunning = TRUE;
			GError *erreur = NULL;
			#ifndef GLIB_VERSION_2_32
			pTask->pThread = g_thread_create ((GThreadFunc) _get_data_threaded, pTask, TRUE, &erreur);  // TRUE <=> joinable
			#else
			pTask->pThread = g_thread_try_new ("Cairo-Dock Task", (GThreadFunc) _get_data_threaded, pTask, &erreur);
			#endif
			if (erreur != NULL)  // on n'a pas pu lancer le thread.
			{
				cd_warning (erreur->message);
				g_error_free (erreur);
				pTask->bIsRunning = FALSE;
			}
		}
		else  // thread already exists; it's either running or sleeping or finished with a pending update
		if (pTask->pCond && g_mutex_trylock (pTask->pMutex))  // it's a periodic thread, and it's not currently running...
		{
			if (pTask->iSidUpdateIdle == 0)  // ...and it doesn't have a pending update -> awake it and run it again.
			{
				pTask->bRunThread = TRUE;
				pTask->bIsRunning = TRUE;
				g_cond_signal (pTask->pCond);
			}
			g_mutex_unlock (pTask->pMutex);
		}  // else it's a one-shot thread or it's currently running or has a pending update -> don't launch it. so if the task is periodic, it will skip this iteration.
	}
}
/*
 * The "expose_event" signal handler for drawingarea1. All OpenGL re-drawing should be done here.
 * This is called every time the expose/draw event is signalled.
 *
 */
gboolean SludgeGLApplication::on_drawingarea1_expose_event(GtkWidget *theWidget, GdkEventExpose *theEvent)
{
	GdkGLContext *glContext;
	GdkGLDrawable *glDrawable;

	// Don't continue if we get fed a dud window type.
	if (theWidget->window == NULL)
	{
		return FALSE;
	}

	/*
	 * Lock rendering mutex if it's not busy - otherwise exit.
	 * This prevents the renderer being spammed by drawing requests if the rendering takes longer than the feed/timer process.
	 */
	if (!g_mutex_trylock(theRender_mutex))
		return FALSE;

	glContext = gtk_widget_get_gl_context (theWidget);
	glDrawable = gtk_widget_get_gl_drawable (theWidget);

	// Signal to gdk the start OpenGL operations.
	if (!gdk_gl_drawable_gl_begin (glDrawable, glContext))
	{
		g_mutex_unlock(theRender_mutex);
		return FALSE;
	}

	drawRect();

	/*
	 * Swap rendering buffers out (an auto glFlush is issued after) if we previously managed to initialise
	 * it as a double-buffered context, otherwise issue a standard glFlush call to signal we've finished
	 * OpenGL rendering.
	 */
	if (gdk_gl_drawable_is_double_buffered (glDrawable))
		gdk_gl_drawable_swap_buffers (glDrawable);
	else
		glFlush ();

	// Signal to gdk we're done with OpenGL operations.
	gdk_gl_drawable_gl_end (glDrawable);

	// Release the rendering mutex.
	g_mutex_unlock(theRender_mutex);

	return FALSE;
}
Ejemplo n.º 30
0
void run_2(Arg *arg)
{
    int i;

    for (i=0; i< arg->max; i++)
    {
        if (g_mutex_trylock(mutex) == FALSE)
        {
            g_print("%d:线程1锁定互斥对象\n", i);
        }else
        {
            g_usleep(10);
        }
    }

    t2_end = TRUE;
}