-
-
Notifications
You must be signed in to change notification settings - Fork 16
/
ConcurrentQueue.h
50 lines (43 loc) · 1.05 KB
/
ConcurrentQueue.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
#pragma once
#include <queue>
#include <mutex>
#include <condition_variable>
template <typename T>
class ConcurrentQueue final
{
private:
std::condition_variable oItemAvailableCondition;
std::condition_variable oIsEmptyCondition;
std::queue<T> oQueue;
std::mutex oQueueMutex;
short iWaiters;
public:
ConcurrentQueue() = default;
T Pop()
{
std::unique_lock<std::mutex> mlock(oQueueMutex);
if (--iWaiters == 0 && oQueue.empty()) oIsEmptyCondition.notify_one();
oItemAvailableCondition.wait(mlock, [&]() noexcept { return !oQueue.empty(); });
auto oQueueItem = oQueue.front();
oQueue.pop();
iWaiters++;
return oQueueItem;
}
void Push(const T& oQueueItem)
{
{
std::lock_guard<std::mutex> mlock(oQueueMutex);
oQueue.push(oQueueItem);
}
oItemAvailableCondition.notify_one();
}
void WaitForEmptyQueues()
{
std::unique_lock<std::mutex> mlock(oQueueMutex);
oIsEmptyCondition.wait(mlock, [&]() noexcept { return iWaiters == 0 && oQueue.empty(); });
}
void SetWaiterCounter(short iWaitCounters)
{
iWaiters = iWaitCounters;
}
};