-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBarrier.cxx
61 lines (57 loc) · 1.15 KB
/
Barrier.cxx
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
#include <chrono>
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <thread>
class BarrierSync
{
public:
BarrierSync(int n): num(n), count(0), generation(0) { }
void sync();
private:
std::condition_variable cv;
std::mutex mtx;
int num, count, generation;
};
void BarrierSync::sync()
{
std::unique_lock<std::mutex> lck(mtx);
if(++count < num)
{
int mygen = generation;
while(mygen == generation)
cv.wait(lck);
}
else
{
count = 0;
generation++;
cv.notify_all();
}
}
int main()
{
const int NUM = 5;
std::thread tid[NUM];
BarrierSync barrier(NUM);
auto unsynced = []() { std::cout<<"----->"<<std::endl; };
for(int i = 0; i < NUM; i++)
{
tid[i] = std::thread(unsynced);
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
for(int i = 0; i < NUM; i++)
tid[i].join();
std::cout<<std::endl;
auto synced = [](BarrierSync& barrier) {
barrier.sync(); std::cout<<"----->"<<std::endl;
};
for(int i = 0; i < NUM; i++)
{
tid[i] = std::thread(synced, std::ref(barrier));
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
for(int i = 0; i < NUM; i++)
tid[i].join();
std::cout<<std::endl;
}