#include <thread>
#include <mutex>
#include <condition_variable>
void thread_print()
{
std::mutex mtx;
condition_variable c;
int n = 100;
bool flag = true;
thread t1([&](){
int i = 0;
while (i < n)
{
unique_lock<mutex> lock(mtx);
c.wait(lock, [&]()->bool{return flag; });
cout << i << endl;
flag = false;
i += 2; // 偶数
c.notify_one();
}
});
thread t2([&](){
int j = 1;
while (j < n)
{
unique_lock<mutex> lock(mtx);
c.wait(lock, [&]()->bool{return !flag; });
cout << j << endl;
j += 2; // 奇数
flag = true;
c.notify_one();
}
});
t1.join();
t2.join();
}
04-15
775
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
09-04
1127
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
09-21
1664
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)