Unblock recvfrom when socket is closed

前端 未结 5 1283
自闭症患者
自闭症患者 2020-12-07 01:44

Let\'s say I start a thread to receive on a port. The socket call will block on recvfrom. Then, somehow in another thread, I close the socket.

On Windows, this will

5条回答
  •  北荒
    北荒 (楼主)
    2020-12-07 02:04

    You are asking for the impossible. There is simply no possible way for the thread that calls close to know that the other thread is blocked in recvfrom. Try to write code that guarantees that this happens, you will find that it is impossible.

    No matter what you do, it will always be possible for the call to close to race with the call to recvfrom. The call to close changes what the socket descriptor refers to, so it can change the semantic meaning of the call to recvfrom.

    There is no way for the thread that enters recvfrom to somehow signal to the thread that calls close that it is blocked (as opposed to being about to block or just entering the system call). So there is literally no possible way to ensure the behavior of close and recvfrom are predictable.

    Consider the following:

    1. A thread is about to call recvfrom, but it gets pre-empted by other things the system needs to do.
    2. Later, the thread calls close.
    3. A thread started by the system's I/O library calls socket and gets the same decsriptor as the one you closed.
    4. Finally, the thread calls recvfrom, and now it's receiving from the socket the library opened.

    Oops.

    Don'd ever do anything even remotely like this. A resource must not be released while another thread is, or might be, using it. Period.

提交回复
热议问题