-
Notifications
You must be signed in to change notification settings - Fork 0
/
safe_queue.h
executable file
·67 lines (58 loc) · 1.16 KB
/
safe_queue.h
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
63
64
65
66
67
#pragma once
//https://stackoverflow.com/questions/15278343/c11-thread-safe-queue //2020 05 28
#include <queue>
#include <mutex>
#include <condition_variable>
// A threadsafe-queue.
template <class T>
class SafeQueue
{
public:
SafeQueue(void)
: q()
, m()
, c()
{ stop = false;}
~SafeQueue(void)
{}
// Add an element to the queue.
void enqueue(T t)
{
std::lock_guard<std::mutex> lock(m);
q.push(t);
c.notify_one();
}
// Get the "front"-element.
// If the queue is empty, wait till a element is avaiable.
T dequeue(void)
{
std::unique_lock<std::mutex> lock(m);
while(q.empty())
{
// release lock as long as the wait and reaquire it afterwards.
c.wait(lock);
if (stop) return nullptr;
}
T val = q.front();
q.pop();
return val;
}
T tryDequeue(void)
{
std::unique_lock<std::mutex> lock(m);
if (q.empty()) return NULL;
T val = q.front();
q.pop();
return val;
}
void Stop(void)
{
stop=true;
c.notify_one();
}
private:
std::queue<T> q;
mutable std::mutex m;
std::condition_variable c;
bool stop;
};