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.

83 lines
1.5KB

  1. template<class T>
  2. SafeQueue<T>::SafeQueue(size_t maxlen)
  3. :writePtr(0), readPtr(0), bufSize(maxlen)
  4. {
  5. sem_init(&w_space, PTHREAD_PROCESS_PRIVATE, maxlen - 1);
  6. sem_init(&r_space, PTHREAD_PROCESS_PRIVATE, 0);
  7. buffer = new T[maxlen];
  8. }
  9. template<class T>
  10. SafeQueue<T>::~SafeQueue()
  11. {
  12. sem_destroy(&w_space);
  13. sem_destroy(&r_space);
  14. delete [] buffer;
  15. }
  16. template<class T>
  17. unsigned int SafeQueue<T>::size() const
  18. {
  19. return rSpace();
  20. }
  21. template<class T>
  22. unsigned int SafeQueue<T>::rSpace() const
  23. {
  24. int space = 0;
  25. sem_getvalue(&r_space, &space);
  26. return space;
  27. }
  28. template<class T>
  29. unsigned int SafeQueue<T>::wSpace() const
  30. {
  31. int space = 0;
  32. sem_getvalue(&w_space, &space);
  33. return space;
  34. }
  35. template<class T>
  36. int SafeQueue<T>::push(const T &in)
  37. {
  38. if(!wSpace())
  39. return -1;
  40. //ok, there is space to write
  41. size_t w = (writePtr + 1) % bufSize;
  42. buffer[w] = in;
  43. writePtr = w;
  44. //adjust ranges
  45. sem_wait(&w_space); //guaranteed not to wait
  46. sem_post(&r_space);
  47. return 0;
  48. }
  49. template<class T>
  50. int SafeQueue<T>::pop(T &out)
  51. {
  52. if(!rSpace())
  53. return -1;
  54. //ok, there is space to read
  55. size_t r = (readPtr + 1) % bufSize;
  56. out = buffer[r];
  57. readPtr = r;
  58. //adjust ranges
  59. sem_wait(&r_space); //guaranteed not to wait
  60. sem_post(&w_space);
  61. return 0;
  62. }
  63. template<class T>
  64. void SafeQueue<T>::clear()
  65. {
  66. //thread unsafe
  67. while(!sem_trywait(&r_space))
  68. sem_post(&w_space);
  69. readPtr = writePtr;
  70. }