当 n = 3N 时,线程1输出
当 n = 3N + 1 时,线程2输出
当 n = 3N + 2 时,线程3输出
最终的输出为 0、1、2、3、4、5、6、7、8、10
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std;
mutex mut;
condition_variable cv;
int N = 0;
void func1() {
unique_lock<mutex> lock(mut);
while (true) {
cv.wait(lock, []{return (N % 3) == 0;});
cout << N << endl;
N++;
cv.notify_all();
}
}
void func2() {
unique_lock<mutex> lock(mut);
while (true) {
cv.wait(lock, []{return (N % 3) == 1;});
cout << N << endl;
N++;
cv.notify_all();
}
}
void func3() {
unique_lock<mutex> lock(mut);
while (true) {
cv.wait(lock, []{return (N % 3) == 2;});
cout << N << endl;
N++;
cv.notify_all();
}
}
int main() {
thread t1(func1);
thread t2(func2);
thread t3(func3);
t1.join();
t2.join();
t3.join();
return 0;
}