Posted By

felipec on 01/23/08


Tagged

glib


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

jeffhung


GLib semaphore


 / Published in: C++
 

  1. typedef struct GSem GSem;
  2.  
  3. struct GSem
  4. {
  5. GCond *condition;
  6. GMutex *mutex;
  7. guint counter;
  8. };
  9.  
  10. GSem *
  11. g_sem_new (void)
  12. {
  13. GSem *sem;
  14.  
  15. sem = g_new (GSem, 1);
  16. sem->condition = g_cond_new ();
  17. sem->mutex = g_mutex_new ();
  18. sem->counter = 0;
  19.  
  20. return sem;
  21. }
  22.  
  23. void
  24. g_sem_free (GSem *sem)
  25. {
  26. g_cond_free (sem->condition);
  27. g_mutex_free (sem->mutex);
  28. g_free (sem);
  29. }
  30.  
  31. void
  32. g_sem_down (GSem *sem)
  33. {
  34. g_mutex_lock (sem->mutex);
  35.  
  36. while (sem->counter == 0)
  37. {
  38. g_cond_wait (sem->condition, sem->mutex);
  39. }
  40.  
  41. sem->counter--;
  42.  
  43. g_mutex_unlock (sem->mutex);
  44. }
  45.  
  46. void
  47. g_sem_up (GSem *sem)
  48. {
  49. g_mutex_lock (sem->mutex);
  50. sem->counter++;
  51. g_cond_signal (sem->condition);
  52. g_mutex_unlock (sem->mutex);
  53. }

Report this snippet  

You need to login to post a comment.