我想從另一個線程(主線程)使用std :: condition_variable發送多個通知到正在運行的線程。發送一次,但第二次或多次都不起作用。這是我做了什麼(不實際事件的不必要的細節):多個std :: condition_variable通知使用notify_one運行線程()
#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
任何意見,將不勝感激。
插入
lk.unlock();
也許你可以清理你的代碼,使其可讀.. –你需要事件的隊列或原子計數器。一個條件變量不記得它被通知了多少次。如果線程沒有在事件之間喚醒並重置條件變量,則第二個通知將不起作用。 –
基本上,而不是'布爾condition_reached;'你需要一個'原子 condition_counter;' –