concurrent_queue.h 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /*
  2. This file is part of cpp-ethereum.
  3. cpp-ethereum is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 3 of the License, or
  6. (at your option) any later version.
  7. cpp-ethereum is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
  13. */
  14. #pragma once
  15. #include <utility>
  16. #include <queue>
  17. #include <condition_variable>
  18. #include <mutex>
  19. namespace dev
  20. {
  21. /// Concurrent queue.
  22. /// You can push and pop elements to/from the queue. Pop will block until the queue is not empty.
  23. /// The default backend (_QueueT) is std::queue. It can be changed to any type that has
  24. /// proper push(), pop(), empty() and front() methods.
  25. template<typename _T, typename _QueueT = std::queue<_T>>
  26. class concurrent_queue
  27. {
  28. public:
  29. template<typename _U>
  30. void push(_U&& _elem)
  31. {
  32. {
  33. std::lock_guard<decltype(x_mutex)> guard{x_mutex};
  34. m_queue.push(std::forward<_U>(_elem));
  35. }
  36. m_cv.notify_one();
  37. }
  38. _T pop()
  39. {
  40. std::unique_lock<std::mutex> lock{x_mutex};
  41. m_cv.wait(lock, [this]{ return !m_queue.empty(); });
  42. auto item = std::move(m_queue.front());
  43. m_queue.pop();
  44. return item;
  45. }
  46. private:
  47. _QueueT m_queue;
  48. std::mutex x_mutex;
  49. std::condition_variable m_cv;
  50. };
  51. }