-
-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathConcurrentQueue.h
More file actions
64 lines (56 loc) · 1.54 KB
/
ConcurrentQueue.h
File metadata and controls
64 lines (56 loc) · 1.54 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
63
64
#pragma once
#include <queue>
#include <mutex>
#include <condition_variable>
#include <utility>
template <typename T>
class ConcurrentQueue final
{
std::condition_variable oItemAvailableCondition;
std::condition_variable oIsEmptyCondition;
std::queue<T> oQueue;
std::mutex oQueueMutex;
int iActiveWorkers = 0;
public:
ConcurrentQueue() = default;
ConcurrentQueue(const ConcurrentQueue&) = delete;
ConcurrentQueue& operator=(const ConcurrentQueue&) = delete;
ConcurrentQueue(ConcurrentQueue&&) = delete;
ConcurrentQueue& operator=(ConcurrentQueue&&) = delete;
T Pop()
{
std::unique_lock<std::mutex> mlock(oQueueMutex);
if (--iActiveWorkers == 0 && oQueue.empty()) oIsEmptyCondition.notify_all();
oItemAvailableCondition.wait(mlock, [this]() noexcept { return !oQueue.empty(); });
T oQueueItem = std::move(oQueue.front());
oQueue.pop();
++iActiveWorkers;
return oQueueItem;
}
void Push(const T& oQueueItem)
{
{
std::lock_guard<std::mutex> mlock(oQueueMutex);
oQueue.push(oQueueItem);
}
oItemAvailableCondition.notify_one();
}
void Push(T&& oQueueItem)
{
{
std::lock_guard<std::mutex> mlock(oQueueMutex);
oQueue.push(std::move(oQueueItem));
}
oItemAvailableCondition.notify_one();
}
void WaitForEmptyQueues()
{
std::unique_lock<std::mutex> mlock(oQueueMutex);
oIsEmptyCondition.wait(mlock, [this]() noexcept { return iActiveWorkers == 0 && oQueue.empty(); });
}
void SetWaiterCounter(short iWaitCounters) noexcept
{
std::lock_guard<std::mutex> mlock(oQueueMutex);
iActiveWorkers = iWaitCounters;
}
};