-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththreadsafe_blocking_queue.h
More file actions
62 lines (51 loc) · 1.32 KB
/
threadsafe_blocking_queue.h
File metadata and controls
62 lines (51 loc) · 1.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#ifndef THREADSAFE_BLOCKING_QUEUE_H
#define THREADSAFE_BLOCKING_QUEUE_H
#include <chrono>
#include <condition_variable>
#include <mutex>
#include <queue>
// TODO: have contructor that sets default timeout for wait_and_pop ?
template <typename T>
class threadsafe_blocking_queue
{
public:
bool empty() const
{
std::lock_guard<std::mutex> lock(access_lock);
return data.empty();
}
void push(const T &value)
{
std::lock_guard<std::mutex> lock(access_lock);
data.push(value);
condition.notify_one();
}
// TODO: return T or shared_ptr<T> ?
T wait_and_pop()
{
std::unique_lock<std::mutex> lock(access_lock);
condition.wait(lock, [this] { return !data.empty(); });
auto value = data.front();
data.pop();
return value;
}
bool timed_wait_and_pop(T &value, const std::chrono::milliseconds &timeout)
{
std::unique_lock<std::mutex> lock(access_lock);
if (condition.wait_for(lock, timeout, [this] { return !data.empty(); }))
{
value = data.front();
data.pop();
return true;
}
else
{
return false;
}
}
private:
mutable std::mutex access_lock;
std::queue<T> data;
std::condition_variable condition;
};
#endif