-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmultiThread.cpp
More file actions
47 lines (42 loc) · 921 Bytes
/
Copy pathmultiThread.cpp
File metadata and controls
47 lines (42 loc) · 921 Bytes
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
#include <iostream>
#include <condition_variable>
#include <mutex>
#include <thread>
std::mutex m;
std::condition_variable cv;
int i = 0;
void print1() {
while (1) {
std::unique_lock<std::mutex> lock(m);
cv.wait(lock, [](){return i % 3 == 0;});
std::cout << "1" << std::endl;
i++;
cv.notify_all();
}
}
void print2() {
while(1) {
std::unique_lock<std::mutex> lock(m);
cv.wait(lock, [](){return i % 3 == 1;});
std::cout << "2" << std::endl;
i++;
cv.notify_all();
}
}
void print3() {
while(1) {
std::unique_lock<std::mutex> lock(m);
cv.wait(lock, [](){return i % 3 == 2;});
std::cout << "3" << std::endl;
i++;
cv.notify_all();
}
}
int main () {
std::thread t1(print1);
std::thread t2(print2);
std::thread t3(print3);
t1.join();
t2.join();
t3.join();
}