我正在尝试使用std :: condition_variable从另一个线程(主线程)向正在运行的线程发送多个通知。发送它一旦工作然而做第二次或多次似乎不起作用。这就是我所做的(没有不必要的实际事件细节):
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <future>
bool keep_running=true;
bool condition_reached=false;
std::mutex cond_mtx;
std::condition_variable cond;
void thread_waiting_to_be_notified(){
while(keep_running){
std::unique_lock<std::mutex> lk(cond_mtx);
cond.wait(lk,[]()->bool{return condition_reached;});
std::cout << "got notitication" << std::endl;
condition_reached=false;
}
}
void some_event(){
/*some event happens here*/
}
void another_event(){
/*another event happens here*/
}
int main(){
std::thread thr(thread_waiting_to_be_notified);
some_event();//first event
std::cout << "some event happened" << std::endl;
condition_reached=true;
cond.notify_one();
another_event();//second event
std::cout << "another event happened" << std::endl;
condition_reached=true;
cond.notify_one();
keep_running=false;
thr.join();
return 0;
}
和我得到的输出
some event happened
another event happened
got notitication
但是,我希望
some event happened
another event happened
got notitication
got notitication
任何建议都将受到赞赏。
答案 0 :(得分:0)
尝试在
之后插入lk.unlock();
condition_reached=false;