blob: 4095c5618dd4d0dba536c0f1640ebbfc630fa05b [file] [log] [blame]
Steven Moreland7e3a2a22016-09-15 09:04:37 -07001#include <condition_variable>
2#include <mutex>
3#include <queue>
4#include <thread>
5
6/* Threadsafe queue.
7 */
8template <typename T>
9struct 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
25private:
26 std::condition_variable mCondition;
27 std::mutex mMutex;
28 std::queue<T> mQueue;
29};
30
31template <typename T>
32T 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
45template <typename T>
46void 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
55template <typename T>
56size_t SynchronizedQueue<T>::size() {
57 std::unique_lock<std::mutex> lock(mMutex);
58
59 return mQueue.size();
60}