如何中断正在等待recv函数的线程? [英] how to interrupt a thread which is waiting on recv function?
问题描述
我有一个挂起recv函数的套接字监听器:
size_t recvLen = recv(sock,buf,512,0 );
我想终止这个线程并中断它。 MSDN说:
当发出阻塞Winsock调用
$ b $
(如recv)时,Winsock可能需要等待
网络事件之前调用
可以完成。 Winsock在这种情况下执行
警报等待,
可以被计划在同一线程上的
异步过程调用(APC)
中断。解决方案您可以中断它通过
QueueUserAPC
将APC排队。但是,在APC中终止线程很可能是不安全的。排队APC不会结束recv
,它只是中断它;一旦APC返回,它将再次回到recv
。
如果要停止
recv
,您应该使用选择
超时,直到数据可用。然后,您可以检查是否应该继续等待数据或在每次超时时继续。I have a socket listener which hangs on recv function:
size_t recvLen = recv(sock, buf, 512, 0);
I would like to terminate this thread with interrupting it. MSDN says:
When issuing a blocking Winsock call such as recv, Winsock may need to wait for a network event before the call can complete. Winsock performs an alertable wait in this situation, which can be interrupted by an asynchronous procedure call (APC) scheduled on the same thread.
How can I do that?
解决方案You can interrupt it by queuing an APC to it via
QueueUserAPC
. However, it's most likely unsafe to terminate the thread in the APC. Queuing an APC doesn't end therecv
, it just interrupts it; once the APC returns, it will go back to waiting onrecv
again.If you want to stop the
recv
completely, you should be usingselect
with a timeout to wait until data is available. You can then check whether you should keep waiting for data or continue at each timeout.这篇关于如何中断正在等待recv函数的线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!