-
Notifications
You must be signed in to change notification settings - Fork 0
/
SafeQueue.h
59 lines (50 loc) · 1.25 KB
/
SafeQueue.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
/* SafeQueue.h
* -----------
* Thread safe queue based on Windows C++/CLI libraries. Designed
* to be used as a producer/consumer queue.
*
* Created by John Whitworth on 6/30/14.
*/
#pragma once
#include <queue>
#include <windows.h>
template <typename T> class SafeQueue
{
private:
std::queue<T> queue;
CRITICAL_SECTION CritSection;
CONDITION_VARIABLE ConditionVar;
public:
SafeQueue(void) {
InitializeCriticalSection(&CritSection);
InitializeConditionVariable(&ConditionVar);
}
~SafeQueue(void) {
DeleteCriticalSection(&CritSection);
}
void add(T item) {
EnterCriticalSection(&CritSection);
queue.push(item);
LeaveCriticalSection(&CritSection);
WakeAllConditionVariable(&ConditionVar);
}
T get() {
EnterCriticalSection(&CritSection);
if (queue.empty()) {
SleepConditionVariableCS(&ConditionVar, &CritSection, INFINITE);
}
T item = queue.front();
queue.pop();
LeaveCriticalSection(&CritSection);
return item;
}
int size() {
EnterCriticalSection(&CritSection);
int size = queue.size();
LeaveCriticalSection(&CritSection);
return size;
}
bool empty() {
return (size() == 0);
}
};