blob: 854851edfd0248eed0144198e7d2334c3358748a [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>
14
15template <typename T>
16class Queue
17{
18 public:
19
20 T pop()
21 {
22 std::unique_lock<std::mutex> mlock(mutex_);
23 while (queue_.empty())
24 {
25 cond_.wait(mlock);
26 }
27 auto val = queue_.front();
28 queue_.pop();
29 return val;
30 }
31
32 void pop(T& item)
33 {
34 std::unique_lock<std::mutex> mlock(mutex_);
35 while (queue_.empty())
36 {
37 cond_.wait(mlock);
38 }
39 item = queue_.front();
40 queue_.pop();
41 }
42
43 void push(const T& item)
44 {
45 std::unique_lock<std::mutex> mlock(mutex_);
46 queue_.push(item);
47 mlock.unlock();
48 cond_.notify_one();
49 }
50 Queue()=default;
51 Queue(const Queue&) = delete; // disable copying
52 Queue& operator=(const Queue&) = delete; // disable assignment
53
54 private:
55 std::queue<T> queue_;
56 std::mutex mutex_;
57 std::condition_variable cond_;
58};
59
60#endif