Implement semaphore

Glib seems to provide mutexes and conditions as primitives for thread synchronization, but as for general semaphores (in the sense that they support the original P and V operations?) Do I understand correctly that it is GCondequivalent to a binary semaphore, moreover, it is g_cond_signalequivalent P, but g_cond_waitequivalent V? But what about semaphores not limited to a maximum value of 1?

I thought of something like this:

struct semaphore {
  int n;
  GMutex sem_lock;
  GCond sem_cond;
}

If the operation Pnow looks something like this:

void semaphore_P (struct semaphore *sem)
{
   g_mutex_lock(sem->sem_lock);
   while (sem->n == 0)
     g_cond_wait(sem->sem_cond, sem->sem_lock);
   --sem->n;
   g_mutex_unlock(sem->sem_lock);
}

Is there an easier way to get pthreads' functionality from sem_waitand sem_postfrom glib?

+3
source share
1 answer

:

  • : GAsyncQueue * queue = g_async_queue_new();

  • V: g_async_queue_push (, GINT_TO_POINTER (1));

  • P: g_async_queue_pop ();

. g_async_queue_push , NULL. , - /, .

.

+2

All Articles