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.

124 lines
2.2KB

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