blob: 30fbbdaa53d8f391c888ffb9b240950674fc1899 [file] [log] [blame]
Shad Ansari01b0e652018-04-05 21:02:53 +00001//
2// Copyright (c) 2013 Juan Palacios juan.palacios.puyana@gmail.com
3// Subject to the BSD 2-Clause License
4// - see < http://opensource.org/licenses/BSD-2-Clause>
5//
6
7#ifndef CONCURRENT_QUEUE_
8#define CONCURRENT_QUEUE_
9
10#include <queue>
11#include <thread>
12#include <mutex>
13#include <condition_variable>
Shad Ansariedef2132018-08-10 22:14:50 +000014#include <chrono>
Shad Ansari01b0e652018-04-05 21:02:53 +000015
16template <typename T>
17class Queue
18{
19 public:
20
Shad Ansariedef2132018-08-10 22:14:50 +000021 std::pair<T, bool> pop(int timeout)
Shad Ansari01b0e652018-04-05 21:02:53 +000022 {
Shad Ansariedef2132018-08-10 22:14:50 +000023 std::cv_status status = std::cv_status::no_timeout;
Shad Ansari01b0e652018-04-05 21:02:53 +000024 std::unique_lock<std::mutex> mlock(mutex_);
Shad Ansariedef2132018-08-10 22:14:50 +000025 static int duration = 0;
Shad Ansari01b0e652018-04-05 21:02:53 +000026 while (queue_.empty())
27 {
Shad Ansariedef2132018-08-10 22:14:50 +000028 status = cond_.wait_for(mlock, std::chrono::seconds(1));
29 if (status == std::cv_status::timeout)
30 {
31 duration++;
32 if (duration > timeout)
33 {
34 duration = 0;
35 return std::pair<T, bool>({}, false);
36 }
37 }
Shad Ansari01b0e652018-04-05 21:02:53 +000038 }
39 auto val = queue_.front();
40 queue_.pop();
Shad Ansariedef2132018-08-10 22:14:50 +000041 return std::pair<T, bool>(val, true);
Shad Ansari01b0e652018-04-05 21:02:53 +000042 }
43
44 void pop(T& item)
45 {
46 std::unique_lock<std::mutex> mlock(mutex_);
47 while (queue_.empty())
48 {
49 cond_.wait(mlock);
50 }
51 item = queue_.front();
52 queue_.pop();
53 }
54
55 void push(const T& item)
56 {
57 std::unique_lock<std::mutex> mlock(mutex_);
58 queue_.push(item);
59 mlock.unlock();
60 cond_.notify_one();
61 }
62 Queue()=default;
63 Queue(const Queue&) = delete; // disable copying
64 Queue& operator=(const Queue&) = delete; // disable assignment
65
66 private:
67 std::queue<T> queue_;
68 std::mutex mutex_;
69 std::condition_variable cond_;
70};
71
72#endif