且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何干净地中断recv调用中的线程阻塞?

更新时间:2022-05-14 22:41:44

因此,您至少具有以下可能性:

So you have at least these possibilities:

(1)pthread_kill将使用errno == EINTR将线程吹出recv,您可以自行清理并退出线程.有人认为这很讨厌.确实取决于.

(1) pthread_kill will blow the thread out of recv with errno == EINTR and you can clean up and exit the thread on your own. Some people think this is nasty. Depends, really.

(2)使您的客户端套接字不阻塞,并使用select在特定时间段内等待输入,然后检查是否已将线程之间使用的开关设置为指示它们应该关闭.

(2) Make your client socket(s) non-blocking and use select to wait on input for a specific period of time before checking if a switch used between the threads has been set to indicated they should shut down.

(3)与(2)组合,使每个线程与主线程共享一个管道.将其添加到select.如果它变得可读并包含关闭请求,则线程将自行关闭.

(3) In combo with (2) have each thread share a pipe with the master thread. Add it to the select. If it becomes readable and contains a shutdonw request, the thread shuts itself down.

(4)如果以上(或其变体)都不满足您的需求,请研究pthread_cancel机制.

(4) Look into the pthread_cancel mechanism if none of the above (or variations thereof) do not meet your needs.