| 1 |
#include <condition_variable> |
| 2 |
#include <mutex> |
| 3 |
#include <queue> |
| 4 |
|
| 5 |
template <typename T> class SynchronizedQueue |
| 6 |
{ |
| 7 |
std::queue<T> queue_; |
| 8 |
std::mutex mutex_; |
| 9 |
std::condition_variable condvar_; |
| 10 |
|
| 11 |
typedef std::lock_guard<std::mutex> lock; |
| 12 |
typedef std::unique_lock<std::mutex> ulock; |
| 13 |
|
| 14 |
public: |
| 15 |
void push(T const &val) |
| 16 |
{ |
| 17 |
lock l(mutex_); // prevents multiple pushes corrupting queue_ |
| 18 |
bool wake = queue_.empty(); // we may need to wake consumer |
| 19 |
queue_.push(val); |
| 20 |
if (wake) condvar_.notify_one(); |
| 21 |
} |
| 22 |
|
| 23 |
T pop() |
| 24 |
{ |
| 25 |
ulock u(mutex_); |
| 26 |
while (queue_.empty()) |
| 27 |
condvar_.wait(u); |
| 28 |
// now queue_ is non-empty and we still have the lock |
| 29 |
T retval = queue_.front(); |
| 30 |
queue_.pop(); |
| 31 |
return retval; |
| 32 |
} |
| 33 |
|
| 34 |
const bool empty() |
| 35 |
{ |
| 36 |
return queue_.empty(); |
| 37 |
} |
| 38 |
}; |