-
Notifications
You must be signed in to change notification settings - Fork 0
/
ThreadQueue.h
93 lines (76 loc) · 1.89 KB
/
ThreadQueue.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/**
* MIT License
* Copyright (c) 2019 Anthony Rabine
*/
#ifndef THREADQUEUE_H
#define THREADQUEUE_H
#include <iostream>
#include <thread>
#include <condition_variable>
#include <queue>
#include <mutex>
#include <chrono>
template<typename Data>
class ThreadQueue
{
public:
void Push(Data const &data)
{
std::lock_guard<std::mutex> lock(mMutex);
mQueue.push(data);
mCondVar.notify_one();
}
bool Empty() const
{
std::lock_guard<std::mutex> lock(mMutex);
return mQueue.empty();
}
bool TryPop(Data &popped_value)
{
std::lock_guard<std::mutex> lock(mMutex);
if (mQueue.empty())
{
return false;
}
popped_value = mQueue.front();
mQueue.pop();
return true;
}
void WaitAndPop(Data &popped_value)
{
std::unique_lock<std::mutex> lock(mMutex);
while (mQueue.empty())
{
mCondVar.wait(lock);
}
popped_value = mQueue.front();
mQueue.pop();
}
bool WaitAndPop(Data &popped_value, uint32_t milliseconds)
{
std::unique_lock<std::mutex> lock(mMutex);
while (mQueue.empty())
{
if (mCondVar.wait_for(lock, std::chrono::milliseconds(milliseconds)) == std::cv_status::timeout)
{
return false;
}
}
popped_value = mQueue.front();
mQueue.pop();
return true;
}
std::uint32_t Size()
{
std::unique_lock<std::mutex> lock(mMutex);
return mQueue.size();
}
private:
std::queue<Data> mQueue;
mutable std::mutex mMutex;
std::condition_variable mCondVar;
};
#endif // THREADQUEUE_H
//=============================================================================
// End of file ThreadQueue.h
//=============================================================================