220-让三个线程循环打印ABC

互斥锁+条件变量实现版本

#include <iostream>
#include <thread>
#include <condition_variable>
#include <mutex>
using namespace std;

condition_variable cv;//条件变量
mutex mx;//互斥量
int isReady = 0;//初始化为0

void printf_1()
{
    unique_lock<mutex> lc(mx);
    int i = 0;
    while(i < 10)
    {
        while(isReady != 0)//如果还没有准备好 那么久开始等待,并且释放锁
            cv.wait(lc);
        cout << "A" ;
        isReady = 1;
        i++;
        cv.notify_all();
    }
}

void printf_2()
{
    unique_lock<mutex> lc(mx);
    int i = 0;
    while(i < 10)
    {
        while(isReady != 1)
            cv.wait(lc);
        cout << "B" ;
        isReady = 2;
        i++;
        cv.notify_all(); //我已经打印完了 轮到别的线程打印了
    }
}

void printf_3()
{
    unique_lock<mutex> lc(mx);
    int i = 0;
    while (i < 10)
    {
        while (isReady != 2)
            cv.wait(lc);
        cout << "C" ;
        isReady = 0;
        i++;
        cv.notify_all(); //我已经打印完了,轮到别的线程打印了
    }
}

int main()
{
    thread t1(printf_1);
    thread t2(printf_2);
    thread t3(printf_3);
    t1.join();
    t2.join();
    t3.join();

    return 0;
}

运行截图如下:
在这里插入图片描述

信号量实现版本

#include <iostream>
#include <thread>
#include <semaphore.h>
using namespace std;

sem_t sem1;
sem_t sem2;
sem_t sem3;

void pthread_fun1()
{
    int i = 0;
    for (; i < 10; ++i)
    {
        sem_wait(&sem1); //P操作
        cout << "A" ;
        std::this_thread::sleep_for(std::chrono::milliseconds(200));
        sem_post(&sem2); //V操作
    }
}
void pthread_fun2()
{
    int i = 0;
    for (; i < 10; ++i)
    {
        sem_wait(&sem2);
        cout << "B" ;
        std::this_thread::sleep_for(std::chrono::milliseconds(200));
        sem_post(&sem3);
    }
}
void pthread_fun3()
{
    int i = 0;
    for (; i < 10; ++i)
    {
        sem_wait(&sem3);
        cout << "C" ;
        std::this_thread::sleep_for(std::chrono::milliseconds(200));
        sem_post(&sem1);
    }
}
int main()
{
    sem_init(&sem1, 0, 1); //初始化
    sem_init(&sem2, 0, 0);
    sem_init(&sem3, 0, 0);
    thread s1(pthread_fun1);
    thread s2(pthread_fun2);
    thread s3(pthread_fun3);
    s1.join();
    s2.join();
    s3.join();

    sem_destroy(&sem1); //销毁信号量
    sem_destroy(&sem2);
    sem_destroy(&sem3);

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

林林林ZEYU

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值