Steven Moreland | 7e3a2a2 | 2016-09-15 09:04:37 -0700 | [diff] [blame] | 1 | #include <condition_variable> |
| 2 | #include <mutex> |
| 3 | #include <queue> |
| 4 | #include <thread> |
| 5 | |
| 6 | /* Threadsafe queue. |
| 7 | */ |
| 8 | template <typename T> |
| 9 | struct SynchronizedQueue { |
| 10 | |
| 11 | /* Gets an item from the front of the queue. |
| 12 | * |
| 13 | * Blocks until the item is available. |
| 14 | */ |
| 15 | T wait_pop(); |
| 16 | |
| 17 | /* Puts an item onto the end of the queue. |
| 18 | */ |
| 19 | void push(const T& item); |
| 20 | |
| 21 | /* Gets the size of the array. |
| 22 | */ |
| 23 | size_t size(); |
| 24 | |
| 25 | private: |
| 26 | std::condition_variable mCondition; |
| 27 | std::mutex mMutex; |
| 28 | std::queue<T> mQueue; |
| 29 | }; |
| 30 | |
| 31 | template <typename T> |
| 32 | T SynchronizedQueue<T>::wait_pop() { |
| 33 | std::unique_lock<std::mutex> lock(mMutex); |
| 34 | |
| 35 | mCondition.wait(lock, [this]{ |
| 36 | return !this->mQueue.empty(); |
| 37 | }); |
| 38 | |
| 39 | T item = mQueue.front(); |
| 40 | mQueue.pop(); |
| 41 | |
| 42 | return item; |
| 43 | } |
| 44 | |
| 45 | template <typename T> |
| 46 | void SynchronizedQueue<T>::push(const T &item) { |
| 47 | { |
| 48 | std::unique_lock<std::mutex> lock(mMutex); |
| 49 | mQueue.push(item); |
| 50 | } |
| 51 | |
| 52 | mCondition.notify_one(); |
| 53 | } |
| 54 | |
| 55 | template <typename T> |
| 56 | size_t SynchronizedQueue<T>::size() { |
| 57 | std::unique_lock<std::mutex> lock(mMutex); |
| 58 | |
| 59 | return mQueue.size(); |
| 60 | } |