如何让一个线程的recv()退出该块优雅? [英] How to let a thread which blocks on recv() exit gracefully?

查看:405
本文介绍了如何让一个线程的recv()退出该块优雅?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个线程喜欢你:

{  
    ......    
    while (1)
    {
        recv(socket, buffer, sizeof(buffer), 0);
        ......
    }
    close(socket);           
}  

由于线程上的recv()阻塞调用,我怎样才能让线程退出优雅?

Because the thread is blocking on recv() call, how can I let the thread exit gracefully?

推荐答案

不要在recv的阻塞。而实施'选择'和测试输入fdset块,以确定是否有任何摆在首位阅读。

Do not block on recv. Rather implement a block on 'select' and test the input fdset to determine if there is anything to read in the first place.

如果存在要读出的数据,可以调用recv。如果没有,回路中,检查isrunning,获取由另一个线程关闭时,已启动设置volitile布尔变量。

If there is data to be read, call recv. If not, loop, check 'isrunning' volitile Boolean variable that gets set by the other thread when shutdown has been initiated.

这篇关于如何让一个线程的recv()退出该块优雅?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆