gpt4 book ai didi

c++ - 线程阻塞等待消息

转载 作者:太空狗 更新时间:2023-10-29 12:07:25 25 4
gpt4 key购买 nike

我有一个 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 上有一个众所周知的技巧,它允许接收线程使用selectpolllisten 套接字 同时出现“条件”[1]。

诀窍是打开从主线程到客户端(接收)线程的管道。 master 在达到某个状态(可以说是信号)时写入管道。客户端(接收)线程可以简单地轮询管道 套接字,并且只检查两者中的哪一个唤醒了它。


[1] 通常 pthread_cond_waitpoll/select 不能在没有竞争的情况下组合,所以你需要编写等待循环超时时间短。相比之下,在 Win32 上它就像 WaitForMultipleObjects 一样简单,你就完成了

关于c++ - 线程阻塞等待消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5781293/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com