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.

SafeQueue.cpp 1.5KB

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