You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

ConcurrentQueue.hpp 1.6 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #pragma once
  2. #ifndef CONCURRENT_QUEUE_HPP
  3. #define CONCURRENT_QUEUE_HPP
  4. #include <queue>
  5. #include <mutex>
  6. #include <utility>
  7. #include <optional>
  8. #undef GetMessage
  9. #undef SendMessage
  10. #undef PeekMessage
  11. template<typename Elem>
  12. class ConcurrentQueue
  13. {
  14. private:
  15. using queueType = std::queue<Elem>;
  16. public:
  17. using sizeType = typename queueType::size_type;
  18. using valueType = typename queueType::value_type;
  19. using reference = typename queueType::reference;
  20. using constReference = typename queueType::const_reference;
  21. using containerType = typename queueType::container_type;
  22. ConcurrentQueue() = default;
  23. ConcurrentQueue(const ConcurrentQueue&) = delete;
  24. ~ConcurrentQueue() noexcept = default;
  25. ConcurrentQueue& operator=(const ConcurrentQueue&) = delete;
  26. void clear()
  27. {
  28. std::scoped_lock<std::mutex> lock(mtx);
  29. while (!q.empty())
  30. q.pop();
  31. }
  32. [[nodiscard]] bool empty() const
  33. {
  34. std::scoped_lock<std::mutex> lock(mtx);
  35. return q.empty();
  36. }
  37. template<typename... Ts>
  38. void emplace(Ts&&... args)
  39. {
  40. std::scoped_lock<std::mutex> lock(mtx);
  41. q.emplace(std::forward<Ts>(args)...);
  42. }
  43. [[nodiscard]] std::optional<valueType> tryPop()
  44. {
  45. std::scoped_lock<std::mutex> lock(mtx);
  46. if (q.empty())
  47. return std::nullopt;
  48. auto out = std::make_optional<valueType>(std::move(q.front()));
  49. q.pop();
  50. return out;
  51. }
  52. private:
  53. mutable std::mutex mtx;
  54. queueType q;
  55. };
  56. #endif