123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155 |
- #ifndef CXXUTIL_THREADSAFE_QUEUE_H_
- #define CXXUTIL_THREADSAFE_QUEUE_H_
- #include <condition_variable>
- #include <mutex>
- #include <queue>
- #include <utility>
- namespace edk {
- template <typename T>
- class ThreadSafeQueue {
- public:
- ThreadSafeQueue() = default;
- ThreadSafeQueue(const ThreadSafeQueue& other) = delete;
- ThreadSafeQueue& operator=(const ThreadSafeQueue& other) = delete;
-
- bool TryPop(T& value);
-
- void WaitAndPop(T& value);
-
- bool WaitAndTryPop(T& value, const std::chrono::microseconds timeout);
-
- void Push(const T& new_value);
-
- void Push(T&& new_value);
-
- bool Empty() {
- std::lock_guard<std::mutex> lk(data_m_);
- return q_.empty();
- }
-
- uint32_t Size() {
- std::lock_guard<std::mutex> lk(data_m_);
- return q_.size();
- }
- private:
- std::mutex data_m_;
- std::queue<T> q_;
- std::condition_variable notempty_cond_;
- };
- template <typename T>
- bool ThreadSafeQueue<T>::TryPop(T& value) {
- std::lock_guard<std::mutex> lk(data_m_);
- if (q_.empty()) {
- return false;
- } else {
- value = q_.front();
- q_.pop();
- return true;
- }
- }
- template <typename T>
- void ThreadSafeQueue<T>::WaitAndPop(T& value) {
- std::unique_lock<std::mutex> lk(data_m_);
- notempty_cond_.wait(lk, [&] { return !q_.empty(); });
- value = q_.front();
- q_.pop();
- }
- template <typename T>
- bool ThreadSafeQueue<T>::WaitAndTryPop(T& value, const std::chrono::microseconds rel_time) {
- std::unique_lock<std::mutex> lk(data_m_);
- if (notempty_cond_.wait_for(lk, rel_time, [&] { return !q_.empty(); })) {
- value = q_.front();
- q_.pop();
- return true;
- } else {
- return false;
- }
- }
- template <typename T>
- void ThreadSafeQueue<T>::Push(const T& new_value) {
- std::lock_guard<std::mutex> lk(data_m_);
- q_.push(new_value);
- notempty_cond_.notify_one();
- }
- template <typename T>
- void ThreadSafeQueue<T>::Push(T&& new_value) {
- std::lock_guard<std::mutex> lk(data_m_);
- q_.push(std::move(new_value));
- notempty_cond_.notify_one();
- }
- }
- #endif
|