C++实现——使用2个线程交替打印A和B
作者:
贺谦
,
2020-10-30 15:24:01
,
所有人可见
,
阅读 916
思路
- C++ 11,VS2019
- 使用了unique_lock,条件变量
- 条件变量的wait(), notify_one()
- wait()中使用了lambda表达式
代码
#include <iostream>
#include <vector>
#include <thread>
#include <list>
#include <mutex>
using namespace std;
bool flag = true;
class A
{
public:
void print1()
{
while (true)
{
std::unique_lock<std::mutex> lock1(print_mutex);
data_var.wait(lock1, [] {return flag; });
cout << "thread: " << std::this_thread::get_id() << " print: " << "A" << endl;
flag = false;
data_var.notify_one();
}
}
void print2()
{
while (true)
{
std::this_thread::sleep_for(std::chrono::seconds(1));
std::unique_lock<std::mutex> lock2(print_mutex);
data_var.wait(lock2, [] {return !flag; });
cout << "thread: " << std::this_thread::get_id() << " print: " << "B" << endl;
flag = true;
data_var.notify_one();
}
}
private:
std::mutex print_mutex;
std::condition_variable data_var;
};
int main()
{
A myobj_a;
std::thread print1(&A::print1, &myobj_a);
std::thread print2(&A::print2, &myobj_a);
print1.join();
print2.join();
return 0;
}
赞一个