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;
}