BlockingQueue.hpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. /*
  2. * Copyright (c)2013-2020 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2025-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #ifndef ZT_BLOCKINGQUEUE_HPP
  14. #define ZT_BLOCKINGQUEUE_HPP
  15. #include <queue>
  16. #include <mutex>
  17. #include <condition_variable>
  18. #include <chrono>
  19. #include <atomic>
  20. #include "../core/Constants.hpp"
  21. namespace ZeroTier {
  22. /**
  23. * Simple C++11 thread-safe queue
  24. *
  25. * Do not use in core/ since we have not gone C++11 there yet.
  26. */
  27. template <class T>
  28. class BlockingQueue
  29. {
  30. public:
  31. enum TimedWaitResult
  32. {
  33. OK,
  34. TIMED_OUT,
  35. STOP
  36. };
  37. ZT_INLINE BlockingQueue(void) : r(true) {}
  38. ZT_INLINE void post(T t)
  39. {
  40. std::lock_guard<std::mutex> lock(m);
  41. q.push(t);
  42. c.notify_one();
  43. }
  44. ZT_INLINE void postLimit(T t,const unsigned long limit)
  45. {
  46. std::unique_lock<std::mutex> lock(m);
  47. for(;;) {
  48. if (q.size() < limit) {
  49. q.push(t);
  50. c.notify_one();
  51. break;
  52. }
  53. if (!r)
  54. break;
  55. gc.wait(lock);
  56. }
  57. }
  58. ZT_INLINE void stop(void)
  59. {
  60. std::lock_guard<std::mutex> lock(m);
  61. r = false;
  62. c.notify_all();
  63. gc.notify_all();
  64. }
  65. ZT_INLINE bool get(T &value)
  66. {
  67. std::unique_lock<std::mutex> lock(m);
  68. if (!r) return false;
  69. while (q.empty()) {
  70. c.wait(lock);
  71. if (!r) {
  72. gc.notify_all();
  73. return false;
  74. }
  75. }
  76. value = q.front();
  77. q.pop();
  78. gc.notify_all();
  79. return true;
  80. }
  81. ZT_INLINE TimedWaitResult get(T &value,const unsigned long ms)
  82. {
  83. const std::chrono::milliseconds ms2{ms};
  84. std::unique_lock<std::mutex> lock(m);
  85. if (!r) return STOP;
  86. while (q.empty()) {
  87. if (c.wait_for(lock,ms2) == std::cv_status::timeout)
  88. return ((r) ? TIMED_OUT : STOP);
  89. else if (!r)
  90. return STOP;
  91. }
  92. value = q.front();
  93. q.pop();
  94. return OK;
  95. }
  96. private:
  97. std::atomic_bool r;
  98. std::queue<T> q;
  99. mutable std::mutex m;
  100. mutable std::condition_variable c,gc;
  101. };
  102. } // namespace ZeroTier
  103. #endif