#ifndef TSQUEUE_H #define TSQUEUE_H /// \cond // C headers // C++ headers #include #include #include #include // 3rd party headers /// \endcond /** * @brief The TSQueue class is a very basic thread-safe queue */ template class TSQueue { public: TSQueue() : mtx(), q(), cv() {} void push(T newVal) { std::lock_guard lck(mtx); q.push(newVal); cv.notify_one(); } void waitAndPop(T& val) { std::unique_lock lck(mtx); cv.wait(lck, [this]{return !q.empty(); }); val = std::move(q.front()); q.pop(); } std::shared_ptr waitAndPop() { std::unique_lock lck(mtx); cv.wait(lck, [this] { return !q.empty(); }); std::shared_ptr res(std::make_shared(std::move(q.front()))); q.pop(); return res; } bool tryPop(T& val) { std::unique_lock lck(mtx); if(q.empty()) { return false; } val = std::move(q.front()); q.pop(); return true; } std::shared_ptr tryPop() { std::unique_lock lck(mtx); if(q.empty()) { return std::shared_ptr(); // nullptr } std::shared_ptr retVal(std::move(q.front())); q.pop(); return retVal; } bool empty() const { std::lock_guard lck(mtx); return q.empty(); } private: mutable std::mutex mtx; std::queue q; std::condition_variable cv; }; #endif // TSQUEUE_H