Go to the documentation of this file.00001
00002
00003
00004 #include <queue>
00005 #include <mutex>
00006 #include <condition_variable>
00007 #include <thread>
00008
00009
00010 template<class T>
00011 class single_consumer_queue
00012 {
00013 std::queue<T> q;
00014 std::mutex mutex;
00015 std::condition_variable cv;
00016
00017 public:
00018 single_consumer_queue<T>() : q(), mutex(), cv() {}
00019
00020 void enqueue(T item)
00021 {
00022 std::unique_lock<std::mutex> lock(mutex);
00023 q.push(std::move(item));
00024 lock.unlock();
00025 cv.notify_one();
00026 }
00027
00028 T dequeue()
00029 {
00030 std::unique_lock<std::mutex> lock(mutex);
00031 const auto ready = [this]() { return !q.empty(); };
00032 if (!ready() && !cv.wait_for(lock, std::chrono::seconds(5), ready)) throw std::runtime_error("Timeout waiting for queued items!");
00033 auto item = std::move(q.front());
00034 q.pop();
00035 return std::move(item);
00036 }
00037
00038 bool try_dequeue(T* item)
00039 {
00040 std::unique_lock<std::mutex> lock(mutex);
00041 if(q.size()>0)
00042 {
00043 auto val = std::move(q.front());
00044 q.pop();
00045 *item = std::move(val);
00046 return true;
00047 }
00048 return false;
00049 }
00050
00051 void clear()
00052 {
00053 std::unique_lock<std::mutex> lock(mutex);
00054 while (q.size() > 0)
00055 {
00056 const auto ready = [this]() { return !q.empty(); };
00057 if (!ready() && !cv.wait_for(lock, std::chrono::seconds(5), ready)) throw std::runtime_error("Timeout waiting for queued items!");
00058 auto item = std::move(q.front());
00059 q.pop();
00060 }
00061
00062
00063 }
00064 size_t size()
00065 {
00066 std::unique_lock<std::mutex> lock(mutex);
00067 return q.size();
00068 }
00069 };
00070
00071 inline bool any_costumers_alive(const std::vector<bool>& running)
00072 {
00073 for (auto is_running : running)
00074 {
00075 if (is_running)
00076 {
00077 return true;
00078 }
00079 }
00080 return false;
00081 }