sem.h 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*
  2. * Copyright (C) 2009 Felipe Contreras
  3. *
  4. * Author: Felipe Contreras <felipe.contreras@gmail.com>
  5. *
  6. * This library is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation
  9. * version 2.1 of the License.
  10. *
  11. * This library is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public
  17. * License along with this library; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  19. *
  20. */
  21. #ifndef SEM_H
  22. #define SEM_H
  23. #include <glib.h>
  24. typedef struct GSem GSem;
  25. struct GSem {
  26. GCond *condition;
  27. GMutex *mutex;
  28. guint count;
  29. };
  30. static inline GSem *
  31. g_sem_new(guint count)
  32. {
  33. GSem *sem;
  34. sem = g_new(GSem, 1);
  35. sem->condition = g_cond_new();
  36. sem->mutex = g_mutex_new();
  37. sem->count = count;
  38. return sem;
  39. }
  40. static inline void
  41. g_sem_free(GSem *sem)
  42. {
  43. g_cond_free(sem->condition);
  44. g_mutex_free(sem->mutex);
  45. g_free(sem);
  46. }
  47. static inline void
  48. g_sem_down(GSem *sem)
  49. {
  50. g_mutex_lock(sem->mutex);
  51. while (sem->count == 0)
  52. g_cond_wait(sem->condition, sem->mutex);
  53. sem->count--;
  54. g_mutex_unlock(sem->mutex);
  55. }
  56. static inline void
  57. g_sem_up(GSem *sem)
  58. {
  59. g_mutex_lock(sem->mutex);
  60. sem->count++;
  61. g_cond_signal(sem->condition);
  62. g_mutex_unlock(sem->mutex);
  63. }
  64. #endif /* SEM_H */