我有一个pthread正在运行并等待来自套接字的消息。线程被阻塞以等待消息,并且在收到新消息之前不会唤醒。有没有办法向线程发送信号以唤醒并让接收函数(recvmsg)返回与信号相关的错误代码?
最佳答案
是的,默认情况下 SIGINT 将中断所有系统调用。来自man recv
:
EINTR The receive was interrupted by delivery of a signal before any
data were available; see signal(7).
and
MSG_WAITALL (since Linux 2.2)
This flag requests that the operation block until the full request is
satisfied. However, the call may still return less data than requested
if a signal is caught, an error or disconnect occurs, or the next
data to be received is of a different type than that returned.
但是,您不能针对特定线程或特定操作。
如果您希望这样做,我建议使用接收线程可以明确监听的条件。 Linux 上有一个众所周知的技巧,允许接收线程使用 select
或 poll
来监听套接字和 同时“条件”[1]。
技巧是打开从主线程到客户端(接收)线程的管道。主设备在达到某种状态(可以说是信号)时写入管道。客户端(接收)线程可以简单地轮询管道和套接字,并仅检查两者中的哪一个唤醒它。
[1] 通常 pthread_cond_wait
和 poll
/select
不能在没有竞赛的情况下组合,因此您需要编写等待循环有小的超时。相比之下,在 Win32 上,它就像 WaitForMultipleObjects
一样简单,然后就完成了
关于c++ - 线程阻塞等待消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5781293/