fifo_buffer.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /*
  2. * fifo_buffer.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_reader_sem( _size ),
  33. m_writer_sem( _size ),
  34. m_reader_index( 0 ),
  35. m_writer_index( 0 ),
  36. m_size( _size )
  37. {
  38. m_buffer = new T[_size];
  39. m_reader_sem.acquire( _size );
  40. }
  41. ~fifoBuffer()
  42. {
  43. delete[] m_buffer;
  44. m_reader_sem.release( m_size );
  45. }
  46. void write( T _element )
  47. {
  48. m_writer_sem.acquire();
  49. m_buffer[m_writer_index++] = _element;
  50. m_writer_index %= m_size;
  51. m_reader_sem.release();
  52. }
  53. T read()
  54. {
  55. m_reader_sem.acquire();
  56. T element = m_buffer[m_reader_index++];
  57. m_reader_index %= m_size;
  58. m_writer_sem.release();
  59. return( element );
  60. }
  61. void waitUntilRead()
  62. {
  63. m_writer_sem.acquire( m_size );
  64. m_writer_sem.release( m_size );
  65. }
  66. bool available()
  67. {
  68. return( m_reader_sem.available() );
  69. }
  70. private:
  71. QSemaphore m_reader_sem;
  72. QSemaphore m_writer_sem;
  73. int m_reader_index;
  74. int m_writer_index;
  75. int m_size;
  76. T * m_buffer;
  77. } ;
  78. #endif