-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBoundedBuffer.h
More file actions
58 lines (51 loc) · 1.56 KB
/
BoundedBuffer.h
File metadata and controls
58 lines (51 loc) · 1.56 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
#ifndef _BOUNDED_BUFFER_H_
#define _BOUNDED_BUFFER_H_
#include <Windows.h>
template <typename T>
class BoundedBuffer {
public:
BoundedBuffer(int);
void put(T);
T get();
~BoundedBuffer();
private:
T *buffer;
int head, tail, capacity;
CRITICAL_SECTION headCriticalSection, tailCriticalSection;
HANDLE itemAvailable, spaceAvailable;
};
template<typename T>
BoundedBuffer<T>::BoundedBuffer(int _capacity) : head(0), tail(0), capacity(_capacity) {
buffer = new T[capacity];
InitializeCriticalSection(&headCriticalSection);
InitializeCriticalSection(&tailCriticalSection);
itemAvailable = CreateSemaphore(NULL, 0, capacity, NULL);
spaceAvailable = CreateSemaphore(NULL, capacity, capacity, NULL);
}
template<typename T>
void BoundedBuffer<T>::put(T data) {
WaitForSingleObject(spaceAvailable, INFINITE);
EnterCriticalSection(&headCriticalSection);
buffer[head] = data;
head = (head + 1) % capacity;
LeaveCriticalSection(&headCriticalSection);
ReleaseSemaphore(itemAvailable, 1, NULL);
}
template<typename T>
T BoundedBuffer<T>::get() {
WaitForSingleObject(itemAvailable, INFINITE);
EnterCriticalSection(&tailCriticalSection);
T retData = buffer[tail];
tail = (tail + 1) % capacity;
LeaveCriticalSection(&tailCriticalSection);
ReleaseSemaphore(spaceAvailable, 1, NULL);
return retData;
}
template<typename T>
BoundedBuffer<T>::~BoundedBuffer() {
DeleteCriticalSection(&headCriticalSection);
DeleteCriticalSection(&tailCriticalSection);
CloseHandle(itemAvailable);
CloseHandle(spaceAvailable);
}
#endif