sem.h 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /*
  2. * Copyright (C) 2009-2010 Felipe Contreras
  3. *
  4. * Author: Felipe Contreras <felipe.contreras@gmail.com>
  5. *
  6. * This file may be used under the terms of the GNU Lesser General Public
  7. * License version 2.1, a copy of which is found in LICENSE included in the
  8. * packaging of this file.
  9. */
  10. #ifndef SEM_H
  11. #define SEM_H
  12. #include <glib.h>
  13. typedef struct GSem GSem;
  14. struct GSem {
  15. GCond *condition;
  16. GMutex *mutex;
  17. guint count;
  18. };
  19. static inline GSem *
  20. g_sem_new(guint count)
  21. {
  22. GSem *sem;
  23. sem = g_new(GSem, 1);
  24. sem->condition = g_cond_new();
  25. sem->mutex = g_mutex_new();
  26. sem->count = count;
  27. return sem;
  28. }
  29. static inline void
  30. g_sem_free(GSem *sem)
  31. {
  32. g_cond_free(sem->condition);
  33. g_mutex_free(sem->mutex);
  34. g_free(sem);
  35. }
  36. static inline void
  37. g_sem_down(GSem *sem)
  38. {
  39. g_mutex_lock(sem->mutex);
  40. while (sem->count == 0)
  41. g_cond_wait(sem->condition, sem->mutex);
  42. sem->count--;
  43. g_mutex_unlock(sem->mutex);
  44. }
  45. static inline bool
  46. g_sem_down_timed(GSem *sem, int seconds)
  47. {
  48. GTimeVal tv;
  49. g_mutex_lock(sem->mutex);
  50. while (sem->count == 0) {
  51. g_get_current_time(&tv);
  52. tv.tv_sec += seconds;
  53. if (!g_cond_timed_wait(sem->condition, sem->mutex, &tv)) {
  54. g_mutex_unlock(sem->mutex);
  55. return false;
  56. }
  57. }
  58. sem->count--;
  59. g_mutex_unlock(sem->mutex);
  60. return true;
  61. }
  62. static inline void
  63. g_sem_up(GSem *sem)
  64. {
  65. g_mutex_lock(sem->mutex);
  66. sem->count++;
  67. g_cond_signal(sem->condition);
  68. g_mutex_unlock(sem->mutex);
  69. }
  70. #endif /* SEM_H */