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.

ZynSema.h 2.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. /*
  2. ZynAddSubFX - a software synthesizer
  3. ZynSema.h - Semaphore Wrapper
  4. Copyright (C) 2016 Mark McCurry
  5. This program is free software; you can redistribute it and/or
  6. modify it under the terms of the GNU General Public License
  7. as published by the Free Software Foundation; either version 2
  8. of the License, or (at your option) any later version.
  9. */
  10. #ifndef ZYNSEMA_H
  11. #define ZYNSEMA_H
  12. #if defined __APPLE__ || defined WIN32
  13. #include <pthread.h>
  14. namespace zyncarla {
  15. class ZynSema
  16. {
  17. public:
  18. ZynSema (void) : _count (0)
  19. {
  20. }
  21. ~ZynSema (void)
  22. {
  23. pthread_mutex_destroy (&_mutex);
  24. pthread_cond_destroy (&_cond);
  25. }
  26. int init (int, int v)
  27. {
  28. _count = v;
  29. return pthread_mutex_init (&_mutex, 0) || pthread_cond_init (&_cond, 0);
  30. }
  31. int post (void)
  32. {
  33. pthread_mutex_lock (&_mutex);
  34. if (++_count == 1) pthread_cond_signal (&_cond);
  35. pthread_mutex_unlock (&_mutex);
  36. return 0;
  37. }
  38. int wait (void)
  39. {
  40. pthread_mutex_lock (&_mutex);
  41. while (_count < 1) pthread_cond_wait (&_cond, &_mutex);
  42. --_count;
  43. pthread_mutex_unlock (&_mutex);
  44. return 0;
  45. }
  46. int trywait (void)
  47. {
  48. if (pthread_mutex_trylock (&_mutex)) return -1;
  49. if (_count < 1)
  50. {
  51. pthread_mutex_unlock (&_mutex);
  52. return -1;
  53. }
  54. --_count;
  55. pthread_mutex_unlock (&_mutex);
  56. return 0;
  57. }
  58. int getvalue (void) const
  59. {
  60. return _count;
  61. }
  62. private:
  63. int _count;
  64. pthread_mutex_t _mutex;
  65. pthread_cond_t _cond;
  66. };
  67. }
  68. #else // POSIX sempahore
  69. #include <semaphore.h>
  70. namespace zyncarla {
  71. class ZynSema
  72. {
  73. public:
  74. ZynSema (void)
  75. {
  76. }
  77. ~ZynSema (void)
  78. {
  79. sem_destroy (&_sema);
  80. }
  81. int init (int s, int v)
  82. {
  83. return sem_init (&_sema, s, v);
  84. }
  85. int post (void)
  86. {
  87. return sem_post (&_sema);
  88. }
  89. int wait (void)
  90. {
  91. return sem_wait (&_sema);
  92. }
  93. int trywait (void)
  94. {
  95. return sem_trywait (&_sema);
  96. }
  97. int getvalue(void)
  98. {
  99. int v = 0;
  100. sem_getvalue(&_sema, &v);
  101. return v;
  102. }
  103. private:
  104. sem_t _sema;
  105. };
  106. }
  107. #endif // POSIX semapore
  108. #endif // ZYNSEMA_H