C++多线程习题:非原创增加注释(02)

模型描述:

  1. 程序开启3个线程,这3个线程的ID分别为A、B、C。
  2. 每个线程将自己的ID在屏幕上打印5遍。
  3. 要求输出结果必须按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;
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值