2016-08-16 94 views
1

我想從另一個線程(主線程)使用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 

任何意見,將不勝感激。

+0

插入lk.unlock();也許你可以清理你的代碼,使其可讀.. –

+1

你需要事件的隊列或原子計數器。一個條件變量不記得它被通知了多少次。如果線程沒有在事件之間喚醒並重置條件變量,則第二個通知將不起作用。 –

+0

基本上,而不是'布爾condition_reached;'你需要一個'原子 condition_counter;' –

回答

0

嘗試後

condition_reached=false; 
+0

謝謝,但不工作! – Pal

+0

剛剛注意到一些有趣的事情。如果函數another_event()的處理時間超過1 ns(納秒),那麼我得到預期的結果...即使沒有lk.unlock()...我在another_event()函數上使用\t \t std :: this_thread :: sleep_for(1ns);然而,實際功能比......短得多,所以我仍然會說它的不可預知的行爲 – Pal

相關問題