diff options
Diffstat (limited to 'thdq.hpp')
-rw-r--r-- | thdq.hpp | 49 |
1 files changed, 49 insertions, 0 deletions
diff --git a/thdq.hpp b/thdq.hpp new file mode 100644 index 0000000..248c807 --- /dev/null +++ b/thdq.hpp @@ -0,0 +1,49 @@ +#pragma once
+
+#include <queue>
+#include <thread>
+#include <mutex>
+#include <condition_variable>
+
+template <typename T>
+class thdq
+{
+public:
+ T pop()
+ {
+ std::unique_lock<std::mutex> mlock(mutex_);
+ while (queue_.empty()) { cond_.wait(mlock); }
+ auto item = std::move(queue_.front());
+ queue_.pop();
+ return item;
+ }
+
+ void pop(T& item)
+ {
+ std::unique_lock<std::mutex> mlock(mutex_);
+ while (queue_.empty()) { cond_.wait(mlock); }
+ item = queue_.front();
+ queue_.pop();
+ }
+
+ void push(const T& item)
+ {
+ std::unique_lock<std::mutex> mlock(mutex_);
+ queue_.push(item);
+ mlock.unlock();
+ cond_.notify_one();
+ }
+
+ void push(T&& item)
+ {
+ std::unique_lock<std::mutex> mlock(mutex_);
+ queue_.push(std::move(item));
+ mlock.unlock();
+ cond_.notify_one();
+ }
+
+private:
+ std::queue<T> queue_;
+ std::mutex mutex_;
+ std::condition_variable cond_;
+}; |