-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBoundedBuffer.h
More file actions
61 lines (49 loc) · 1.27 KB
/
BoundedBuffer.h
File metadata and controls
61 lines (49 loc) · 1.27 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
#ifndef BoundedBuffer_h
#define BoundedBuffer_h
#include <iostream>
#include <queue>
#include <string>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std;
class BoundedBuffer
{
private:
int cap;
queue<vector<char>> q;
/* mutex to protect the queue from simultaneous producer accesses
or simultaneous consumer accesses */
mutex mtx;
/* condition that tells the consumers that some data is there */
condition_variable data_available;
/* condition that tells the producers that there is some slot available */
condition_variable slot_available;
public:
BoundedBuffer(int _cap){
cap = _cap;
}
~BoundedBuffer(){
//potentially need to delete mutex
}
void push(vector<char> data){
//putting item on queue
unique_lock<mutex> lck(mtx);
//need to wait for open slot available
slot_available.wait(lck,[this]{return q.size()<cap;});
q.push(data);
data_available.notify_one();
return;
}
vector<char> pop(){
vector<char> temp;
unique_lock<mutex> lck(mtx);
//need to wait for data available
data_available.wait(lck,[this]{return q.size()>0;});
temp = q.front();
q.pop();
slot_available.notify_one();
return temp;
}
};
#endif /* BoundedBuffer_ */