模型描述:
- 程序开启3个线程,这3个线程的ID分别为A、B、C。
- 每个线程将自己的ID在屏幕上打印5遍。
- 要求输出结果必须按ABC的顺序显示;如:ABCABC….依次递推
#include <iostream>
#include <thread>
#include <mutex>
#include <chrono>
int main()
{
int cnt = 0;
std::mutex mtx;
auto work = [&](char id, int num)
{
while (num--)
{
/*
** 当前线程ID(id)与目标线程ID不匹配时让出时间
** 因此在首次线程B(t2)与C(main)先运行时,会让出其时间
*/
while (id != cnt + 'A')
std::this_thread::yield();
/*
** 锁定并执行任务
*/
std::unique_lock<std::mutex> lk(mtx);
std::cout << id;
/*
** 递增到下一个线程需要的标记值(这里是引用捕获cnt)
** 当cnt=0时,匹配线程A(t1)
** 当cnt=1时,匹配线程B(t2)
** 当cnt=2时,匹配线程C(main)
*/
cnt = (cnt + 1) % 3;
/*
** 解锁
*/
lk.unlock();
std::this_thread::sleep_for(std::chrono::seconds(1));
}
};
std::thread t1(work, 'A', 5);
std::thread t2(work, 'B', 5);
work('C', 5);
t1.join();
t2.join();
return 0;
}

被折叠的 条评论
为什么被折叠?



