2016-03-30 92 views
0

我有一個服務器監聽某個端口,並且我創建了幾個分離的線程。C++線程:如何發送消息到其他長線程?

不僅自己的服務器將永遠運行,而且分離的線程將永遠運行。

//pseudocode 
void t1_func() 
{ 
    for(;;) 
    { 
    if(notified from server) 
     dosomething(); 
    } 
} 
thread t1(t1_func); 
thread t2(...); 
for(;;) 
{ 
    // read from accepted socket 
    string msg = socket.read_some(...); 
    //notify thread 1 and thread 2; 
} 

由於我是新來的多線程,我不知道如何在分離線程實現這樣nofity在服務器和check the nofity

任何有用的提示將不勝感激。

+0

'std :: condition_variable'。 –

回答

0

最簡單的方法是使用std::condition_variablestd::condition_variable將等待另一個線程調用notify_onenotify_all,然後纔會喚醒。

這是你的t1_func實現使用條件變量:

std::condition_variable t1_cond; 
void t1_func() 
{ 
    //wait requires a std::unique_lock 
    std::mutex mtx; 
    std::unique_lock<std::mutex> lock{ mtx }; 
    while(true) 
    { 
     t1_cond.wait(lock); 
     doSomething(); 
    } 
} 

wait方法採用std::unique_lock但鎖沒有被共享通知線程。當你想醒來,從主線程的工作線程,你會打電話notify_onenotify_all這樣的:

t1_cond.notify_one(); 

如果你想擁有的線程喚醒了一定的時間後,你可以使用wait_for代替wait

+0

調用'notify',工人'doSomething()'後,工作線程是否仍然等待下一個通知? – chenzhongpu

+0

@ChenZhongPu是的,每次調用wait()時,都會等待通知。 – phantom