ThreadSafeQueue.h 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. // David Eberly, Geometric Tools, Redmond WA 98052
  2. // Copyright (c) 1998-2020
  3. // Distributed under the Boost Software License, Version 1.0.
  4. // https://www.boost.org/LICENSE_1_0.txt
  5. // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
  6. // Version: 4.0.2019.08.13
  7. #pragma once
  8. #include <mutex>
  9. #include <queue>
  10. namespace WwiseGTE
  11. {
  12. template <typename Element>
  13. class ThreadSafeQueue
  14. {
  15. public:
  16. // Construction and destruction.
  17. ThreadSafeQueue(size_t maxNumElements = 0)
  18. :
  19. mMaxNumElements(maxNumElements)
  20. {
  21. }
  22. virtual ~ThreadSafeQueue() = default;
  23. // All the operations are thread-safe.
  24. size_t GetMaxNumElements() const
  25. {
  26. size_t maxNumElements;
  27. mMutex.lock();
  28. {
  29. maxNumElements = mMaxNumElements;
  30. }
  31. mMutex.unlock();
  32. return maxNumElements;
  33. }
  34. size_t GetNumElements() const
  35. {
  36. size_t numElements;
  37. mMutex.lock();
  38. {
  39. numElements = mQueue.size();
  40. }
  41. mMutex.unlock();
  42. return numElements;
  43. }
  44. bool Push(Element const& element)
  45. {
  46. bool pushed;
  47. mMutex.lock();
  48. {
  49. if (mQueue.size() < mMaxNumElements)
  50. {
  51. mQueue.push(element);
  52. pushed = true;
  53. }
  54. else
  55. {
  56. pushed = false;
  57. }
  58. }
  59. mMutex.unlock();
  60. return pushed;
  61. }
  62. bool Pop(Element& element)
  63. {
  64. bool popped;
  65. mMutex.lock();
  66. {
  67. if (mQueue.size() > 0)
  68. {
  69. element = mQueue.front();
  70. mQueue.pop();
  71. popped = true;
  72. }
  73. else
  74. {
  75. popped = false;
  76. }
  77. }
  78. mMutex.unlock();
  79. return popped;
  80. }
  81. protected:
  82. size_t mMaxNumElements;
  83. std::queue<Element> mQueue;
  84. mutable std::mutex mMutex;
  85. };
  86. }