BlockingQueue.hpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2017 ZeroTier, Inc. https://www.zerotier.com/
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. * --
  19. *
  20. * You can be released from the requirements of the license by purchasing
  21. * a commercial license. Buying such a license is mandatory as soon as you
  22. * develop commercial closed-source software that incorporates or links
  23. * directly against ZeroTier software without disclosing the source code
  24. * of your own application.
  25. */
  26. #ifndef ZT_BLOCKINGQUEUE_HPP
  27. #define ZT_BLOCKINGQUEUE_HPP
  28. #include <queue>
  29. #include <mutex>
  30. #include <condition_variable>
  31. namespace ZeroTier {
  32. /**
  33. * Simple C++11 thread-safe queue
  34. *
  35. * Do not use in node/ since we have not gone C++11 there yet.
  36. */
  37. template <class T>
  38. class BlockingQueue
  39. {
  40. public:
  41. BlockingQueue(void) {}
  42. inline void post(T t)
  43. {
  44. std::lock_guard<std::mutex> lock(m);
  45. q.push(t);
  46. c.notify_one();
  47. }
  48. inline T get(void)
  49. {
  50. std::unique_lock<std::mutex> lock(m);
  51. while(q.empty())
  52. c.wait(lock);
  53. T val = q.front();
  54. q.pop();
  55. return val;
  56. }
  57. private:
  58. std::queue<T> q;
  59. mutable std::mutex m;
  60. std::condition_variable c;
  61. };
  62. } // namespace ZeroTier
  63. #endif