Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

113 lines
1.9KB

  1. #ifndef ZYNSEMA_H
  2. #define ZYNSEMA_H
  3. #if defined __APPLE__ || defined WIN32
  4. #include <pthread.h>
  5. class ZynSema
  6. {
  7. public:
  8. ZynSema (void) : _count (0)
  9. {
  10. }
  11. ~ZynSema (void)
  12. {
  13. pthread_mutex_destroy (&_mutex);
  14. pthread_cond_destroy (&_cond);
  15. }
  16. int init (int, int v)
  17. {
  18. _count = v;
  19. return pthread_mutex_init (&_mutex, 0) || pthread_cond_init (&_cond, 0);
  20. }
  21. int post (void)
  22. {
  23. pthread_mutex_lock (&_mutex);
  24. if (++_count == 1) pthread_cond_signal (&_cond);
  25. pthread_mutex_unlock (&_mutex);
  26. return 0;
  27. }
  28. int wait (void)
  29. {
  30. pthread_mutex_lock (&_mutex);
  31. while (_count < 1) pthread_cond_wait (&_cond, &_mutex);
  32. --_count;
  33. pthread_mutex_unlock (&_mutex);
  34. return 0;
  35. }
  36. int trywait (void)
  37. {
  38. if (pthread_mutex_trylock (&_mutex)) return -1;
  39. if (_count < 1)
  40. {
  41. pthread_mutex_unlock (&_mutex);
  42. return -1;
  43. }
  44. --_count;
  45. pthread_mutex_unlock (&_mutex);
  46. return 0;
  47. }
  48. int getvalue (void) const
  49. {
  50. return _count;
  51. }
  52. private:
  53. int _count;
  54. pthread_mutex_t _mutex;
  55. pthread_cond_t _cond;
  56. };
  57. #else // POSIX sempahore
  58. #include <semaphore.h>
  59. class ZynSema
  60. {
  61. public:
  62. ZynSema (void)
  63. {
  64. }
  65. ~ZynSema (void)
  66. {
  67. sem_destroy (&_sema);
  68. }
  69. int init (int s, int v)
  70. {
  71. return sem_init (&_sema, s, v);
  72. }
  73. int post (void)
  74. {
  75. return sem_post (&_sema);
  76. }
  77. int wait (void)
  78. {
  79. return sem_wait (&_sema);
  80. }
  81. int trywait (void)
  82. {
  83. return sem_trywait (&_sema);
  84. }
  85. int getvalue(void)
  86. {
  87. int v = 0;
  88. sem_getvalue(&_sema, &v);
  89. return v;
  90. }
  91. private:
  92. sem_t _sema;
  93. };
  94. #endif // POSIX semapore
  95. #endif // ZYNSEMA_H