Shad Ansari | 01b0e65 | 2018-04-05 21:02:53 +0000 | [diff] [blame] | 1 | // |
| 2 | // Copyright (c) 2013 Juan Palacios juan.palacios.puyana@gmail.com |
| 3 | // Subject to the BSD 2-Clause License |
| 4 | // - see < http://opensource.org/licenses/BSD-2-Clause> |
| 5 | // |
| 6 | |
| 7 | #ifndef CONCURRENT_QUEUE_ |
| 8 | #define CONCURRENT_QUEUE_ |
| 9 | |
| 10 | #include <queue> |
| 11 | #include <thread> |
| 12 | #include <mutex> |
| 13 | #include <condition_variable> |
Shad Ansari | edef213 | 2018-08-10 22:14:50 +0000 | [diff] [blame] | 14 | #include <chrono> |
Shad Ansari | 01b0e65 | 2018-04-05 21:02:53 +0000 | [diff] [blame] | 15 | |
| 16 | template <typename T> |
| 17 | class Queue |
| 18 | { |
| 19 | public: |
| 20 | |
Shad Ansari | edef213 | 2018-08-10 22:14:50 +0000 | [diff] [blame] | 21 | std::pair<T, bool> pop(int timeout) |
Shad Ansari | 01b0e65 | 2018-04-05 21:02:53 +0000 | [diff] [blame] | 22 | { |
Shad Ansari | edef213 | 2018-08-10 22:14:50 +0000 | [diff] [blame] | 23 | std::cv_status status = std::cv_status::no_timeout; |
Shad Ansari | 01b0e65 | 2018-04-05 21:02:53 +0000 | [diff] [blame] | 24 | std::unique_lock<std::mutex> mlock(mutex_); |
Shad Ansari | edef213 | 2018-08-10 22:14:50 +0000 | [diff] [blame] | 25 | static int duration = 0; |
Shad Ansari | 01b0e65 | 2018-04-05 21:02:53 +0000 | [diff] [blame] | 26 | while (queue_.empty()) |
| 27 | { |
Shad Ansari | edef213 | 2018-08-10 22:14:50 +0000 | [diff] [blame] | 28 | status = cond_.wait_for(mlock, std::chrono::seconds(1)); |
| 29 | if (status == std::cv_status::timeout) |
| 30 | { |
| 31 | duration++; |
| 32 | if (duration > timeout) |
| 33 | { |
| 34 | duration = 0; |
| 35 | return std::pair<T, bool>({}, false); |
| 36 | } |
| 37 | } |
Shad Ansari | 01b0e65 | 2018-04-05 21:02:53 +0000 | [diff] [blame] | 38 | } |
| 39 | auto val = queue_.front(); |
| 40 | queue_.pop(); |
Shad Ansari | edef213 | 2018-08-10 22:14:50 +0000 | [diff] [blame] | 41 | return std::pair<T, bool>(val, true); |
Shad Ansari | 01b0e65 | 2018-04-05 21:02:53 +0000 | [diff] [blame] | 42 | } |
| 43 | |
| 44 | void pop(T& item) |
| 45 | { |
| 46 | std::unique_lock<std::mutex> mlock(mutex_); |
| 47 | while (queue_.empty()) |
| 48 | { |
| 49 | cond_.wait(mlock); |
| 50 | } |
| 51 | item = queue_.front(); |
| 52 | queue_.pop(); |
| 53 | } |
| 54 | |
| 55 | void push(const T& item) |
| 56 | { |
| 57 | std::unique_lock<std::mutex> mlock(mutex_); |
| 58 | queue_.push(item); |
| 59 | mlock.unlock(); |
| 60 | cond_.notify_one(); |
| 61 | } |
| 62 | Queue()=default; |
| 63 | Queue(const Queue&) = delete; // disable copying |
| 64 | Queue& operator=(const Queue&) = delete; // disable assignment |
| 65 | |
| 66 | private: |
| 67 | std::queue<T> queue_; |
| 68 | std::mutex mutex_; |
| 69 | std::condition_variable cond_; |
| 70 | }; |
| 71 | |
| 72 | #endif |