FifoBuffer.h 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /*
  2. * FifoBuffer.h - FIFO fixed-size buffer
  3. *
  4. * Copyright (c) 2007 Javier Serrano Polo <jasp00/at/users.sourceforge.net>
  5. *
  6. * This file is part of LMMS - https://lmms.io
  7. *
  8. * This program is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU General Public
  10. * License as published by the Free Software Foundation; either
  11. * version 2 of the License, or (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. * General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public
  19. * License along with this program (see COPYING); if not, write to the
  20. * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
  21. * Boston, MA 02110-1301 USA.
  22. *
  23. */
  24. #ifndef FIFO_BUFFER_H
  25. #define FIFO_BUFFER_H
  26. #include <QtCore/QSemaphore>
  27. template<typename T>
  28. class FifoBuffer
  29. {
  30. public:
  31. FifoBuffer(int size) :
  32. m_readSem(size),
  33. m_writeSem(size),
  34. m_readIndex(0),
  35. m_writeIndex(0),
  36. m_size(size)
  37. {
  38. m_buffer = new T[size];
  39. m_readSem.acquire(size);
  40. }
  41. ~FifoBuffer()
  42. {
  43. delete[] m_buffer;
  44. m_readSem.release(m_size);
  45. }
  46. void write(T element)
  47. {
  48. m_writeSem.acquire();
  49. m_buffer[m_writeIndex++] = element;
  50. m_writeIndex %= m_size;
  51. m_readSem.release();
  52. }
  53. T read()
  54. {
  55. m_readSem.acquire();
  56. T element = m_buffer[m_readIndex++];
  57. m_readIndex %= m_size;
  58. m_writeSem.release();
  59. return element;
  60. }
  61. void waitUntilRead()
  62. {
  63. m_writeSem.acquire(m_size);
  64. m_writeSem.release(m_size);
  65. }
  66. bool available()
  67. {
  68. return m_readSem.available();
  69. }
  70. private:
  71. QSemaphore m_readSem;
  72. QSemaphore m_writeSem;
  73. int m_readIndex;
  74. int m_writeIndex;
  75. int m_size;
  76. T * m_buffer;
  77. } ;
  78. #endif