-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path014_condition_variable.cpp
More file actions
64 lines (52 loc) · 1.26 KB
/
Copy path014_condition_variable.cpp
File metadata and controls
64 lines (52 loc) · 1.26 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
// Copyright (c) 2012-2013
// Akira Takahashi, Toshihiko Ando, Kohsuke Yuasa,
// Yusuke Ichinohe, Masaya Kusuda, wraith.
// Released under the CC0 1.0 Universal license.
#include <iostream>
#include <deque>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std;
template <class T>
struct LockedQueue {
explicit LockedQueue(int capacity)
: capacity(capacity)
{}
void enqueue(const T& x) {
unique_lock<mutex> lock(m);
c_enq.wait(lock, [this] { return data.size() != capacity; });
data.push_back(x);
c_deq.notify_one();
}
T dequeue() {
unique_lock<mutex> lock(m);
c_deq.wait(lock, [this] { return !data.empty(); });
T ret = data.front();
data.pop_front();
c_enq.notify_one();
return ret;
}
private:
mutex m;
deque<T> data;
size_t capacity;
condition_variable c_enq;
condition_variable c_deq;
};
void worker(LockedQueue<int>& lq) {
for (int i = 0; i < 5; ++i) {
lq.enqueue(i);
this_thread::sleep_for(chrono::milliseconds(100));
}
}
int main() {
LockedQueue<int> lq(2);
thread th(worker, std::ref(lq));
this_thread::sleep_for(chrono::milliseconds(1000));
for (int i = 0; i < 5; ++i) {
int n = lq.dequeue();
cout << "popped : " << n << endl;
}
th.join();
}