c++ 并发 -- “你一下我一下模式“ == 生产者消费者模式

c++ 并发 – “你一下我一下模式” == 生产者消费者模式

利用了 start_send 控制了等待顺序,m_cond 会先执行等待
注意send_run中一定是先m_cond.notify_all() 后 wait,因为如果都是先wait就会造成第二次循环的时候死锁,m_cond 在wait 的同时 m_cond_t 也在wait,在相互等

#include <iostream>
#include <stdio.h>
#include <unistd.h>
#include <condition_variable>
#include <thread>

std::condition_variable m_cond;
std::condition_variable m_cond_t;
std::mutex mutex_;
std::mutex mutex_t;
bool start_state = false;
bool start_send = false;

bool is_varaible()
{
    return start_state;
}

void start_run() 
{
    std::unique_lock<std::mutex> lck(mutex_);
    printf("m_cond wait\r\n");
    if (start_state) {
        m_cond.wait(lck);
    }
    start_send = false;
    m_cond_t.notify_all();
    printf("m_cond wait end\r\n");
    lck.unlock();
}

void thread_func() {
    while(true) {
        start_run();
    }
}

void send_run()
{
    std::unique_lock<std::mutex> lck(mutex_);
    printf("main run\r\n");
    m_cond.notify_all();
    if(!start_send) {
        printf("main wait start\r\n");
        m_cond_t.wait(lck);
    }
}

int main()
{
    std::thread mythread;
    start_state = true;
    start_send = true;
    mythread = std::thread(thread_func);
    while(true) {
        sleep(1);
        send_run();
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值