代码
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std;
mutex mtx;
condition_variable cv;
bool flag = true;
void print(char c)
{
cout << c << endl;
}
void print_first_half()
{
for (char c = 'a'; c <= 'z'; c += 2)
{
unique_lock<mutex> lock(mtx);
cv.wait(lock, [](){ return flag; });
print(c);
flag = false;
cv.notify_one();
}
}
void print_second_half()
{
for (char c = 'b'; c <= 'z'; c += 2)
{
unique_lock<mutex> lock(mtx);
cv.wait(lock, [](){ return !flag; });
print(c);
flag = true;
cv.notify_one();
}
}
int main()
{
thread t1(print_first_half);
thread t2(print_second_half);
t1.join();
t2.join();
return 0;
}
标签:26,return,lock,打印,flag,线程,print,include,cv
From: https://www.cnblogs.com/JohnRan/p/17232123.html