如何中断正在等待recv函数的线程? [英] how to interrupt a thread which is waiting on recv function?

查看:853
本文介绍了如何中断正在等待recv函数的线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个挂起recv函数的套接字监听器:

  size_t recvLen = recv(sock,buf,512,0 ); 

我想终止这个线程并中断它。 MSDN说:


当发出阻塞Winsock调用
(如recv)时,Winsock可能需要等待
网络事件之前调用
可以完成。 Winsock在这种情况下执行
警报等待,
可以被计划在同一线程上的
异步过程调用(APC)
中断。

$ b $

解决方案

您可以中断它通过 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 the recv, it just interrupts it; once the APC returns, it will go back to waiting on recv again.

If you want to stop the recv completely, you should be using select 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屋!

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