2016-03-30 93 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