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.

84 lines
1.9KB

  1. #pragma once
  2. #include <vector>
  3. #include <memory>
  4. #include "RingBuffer.h"
  5. /**
  6. * A very specialized container. Made for holding one free
  7. * work buffers, and making sure they are destroyed.
  8. *
  9. * At construction time, objects are created to fill the pool.
  10. * pop the objects to get one, push back to return when done.
  11. *
  12. * Destructor will delete all the objects, even if they are not in the pool
  13. * at the time.
  14. *
  15. * Note that unlike RingBuffer, ManagePool manages T*, not T.
  16. *
  17. * All public functions are no-blocking, so may be called from the audio thread
  18. * without danger. Of course the constructor and destructor are exceptions - they may block.
  19. */
  20. template <typename T, int SIZE>
  21. class ManagedPool
  22. {
  23. public:
  24. ManagedPool();
  25. /** Accessors from RingBuffer
  26. */
  27. void push(T*);
  28. T* pop();
  29. bool full() const;
  30. bool empty() const;
  31. private:
  32. /**
  33. * this ring buffer is where the raw T* are kept.
  34. * client pops and pushes here
  35. */
  36. RingBuffer<T*, SIZE> ringBuffer;
  37. std::vector< std::unique_ptr<T>> lifetimeManager;
  38. };
  39. template <typename T, int SIZE>
  40. inline ManagedPool<T, SIZE>::ManagedPool()
  41. {
  42. // Manufacture the items here
  43. for (int i = 0; i < SIZE; ++i) {
  44. T * item = new T();
  45. ringBuffer.push(item); // put the raw pointer in ring buffer for client to use.
  46. // Also add managed pointers to delete the objects on destroy.
  47. lifetimeManager.push_back(std::unique_ptr<T>(item));
  48. }
  49. }
  50. template <typename T, int SIZE>
  51. inline void ManagedPool<T, SIZE>::push(T* value)
  52. {
  53. ringBuffer.push(value);
  54. }
  55. template <typename T, int SIZE>
  56. inline T* ManagedPool<T, SIZE>::pop()
  57. {
  58. return ringBuffer.pop();
  59. }
  60. template <typename T, int SIZE>
  61. inline bool ManagedPool<T, SIZE>::full() const
  62. {
  63. return ringBuffer.full();
  64. }
  65. template <typename T, int SIZE>
  66. inline bool ManagedPool<T, SIZE>::empty() const
  67. {
  68. return ringBuffer.empty();
  69. }