如何退出 Windows 中的阻塞 recv()?

How to exit a blocking recv() in Windows?

我有一个包含阻塞 recv() 调用的线程,如下所示:

{   
    while(1)
    {
        recv(socket, buffer, sizeof(buffer), 0);
    }       
}

现在我要做的是从另一个线程向 recv() 函数发出信号,使其退出阻塞状态。我已经阅读了另一个关于如何在 Unix 中执行此操作的问题的答案 (How to let a thread which blocks on recv() exit gracefully?):

Either:

  1. Set a read timeout, with setsockopt() and SO_RCVTIMEO, and whenever it triggers check a state variable to see if you've told yourself to stop reading.
  2. If you want to stop reading the socket forever, shut it down for input with shutdown(sd, SHUT_RD). This will cause recv() to return zero from now on.
  3. Set the socket into non-blocking mode and use select() with a timeout to tell you when to read, adopting the same strategy with a state variable as at (1) above. However non-blocking mode introduces considerable complications into the send operation, so you should prefer (1) or (2) above.

Your pseudo-code lacks EOS- and error-checking. I hope it doesn't really look like that.

我对第一个和第三个解决方案不感兴趣,因为 CPU 可能会耗尽,并且根据我的测试,Windows 不支持第二个解决方案(我说得对吗? ).那么有没有另一种解决方案来退出阻塞recv()

A 阻塞 recv() 仅在以下情况下退出:

  1. 数据读取完毕

  2. 读取超时(SO_RCVTIMEO)。

  3. 连接已关闭

如果这些选项中的 none 对您来说可行,您将不得不简单地不在阻塞模式下调用 recv(),直到您知道有内容等待读取,如 [= 报道的那样12=]、WSAAsyncSelect()WSAEventSelect()

否则,将您的套接字逻辑重写为:

  1. 在非阻塞模式下使用套接字。

  2. 使用 WSARecv()RIOReceive/Ex() 与重叠 I/O 或 I/O 完成端口。可以使用 CancelIo/Ex().

  3. 取消 I/O 操作