Glib Semaphores




Since glib already provides Mutex and Conditional_Signals, it would
seem like a good idea to provide a common usage of those in the
form of Semaphores.  Many threading codes in text books are commonly
expressed in terms of semaphores as there are conceptually simple
to do things like lock step producer/consumer, flow combining and
one pass.  

The total amount of necessary code is minimal as it uses the high
level interface.  It is all of 50 lines... (This is just
example, I have not fully tested it.)

--------------------------------------------------------------------
struct _GSemaphore 
{
  gint value;
  GMutex* access;
  GCond* sig;
};

typedef struct _GSemaphore GSemaphore;
#define g_semaphore_new() g_semaphore_new_with_value(1)
GSemaphore* g_semaphore_new_with_value(gint value);
void g_semaphore_free(GSemaphore*);
void g_semaphore_up(GSemaphore*);
void g_semaphore_down(GSemaphore*);
---------------------------------------------------------------------
GSemaphore* g_semaphore_new_with_value (gint value)
{
  if (!g_thread_supported ())
    return NULL;
  
  GSemaphore *sema = (GSemaphore *) g_new ( GSemaphore, 1);
  sema -> value = value;
  sema -> access = g_mutex_new();
  sema -> sig = g_cond_new();
}

void g_semaphore_free(GSemaphore*)
{
  g_return_if_fail (sema != NULL);
  g_mutex_free (sema->access);
  g_cond_free (sema->sig); 
}

void g_semaphore_up(GSemaphore* sema)
{
  g_return_if_fail (sema != NULL);
  g_mutex_lock (sema->access);
  sema->value ++;
  g_mutex_unlock (sema->access);
  g_cond_signal (sema->signal);
}

void g_semaphore_down(GSemaphore* sema)
{
   g_return_if_fail (sema != NULL);
   g_mutex_lock (sema->access);
   while (sema->value<1)
     g_cond_wait (sema->sig,sema->access);
   sema->value --;
   g_mutex_unlock (sema->access);
}
--------------------------------------------------------------------

We could even define an abstract semaphore with a vfunc up_action, 
down_action, and pass routine, but I think just a basic 
semaphore is useful enough.

Does this sound like a reasonable thing to add to glib?

--Karl




[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]