Can a socket be closed from another thread when a send / recv on the same socket is going on?

后端 未结 5 1121
刺人心
刺人心 2021-02-02 15:48

Can a socket be closed from another thread when a send / recv on the same socket is going on?

Suppose one thread is in blocking recv call and another thread closes the s

5条回答
  •  不知归路
    2021-02-02 16:19

    I don't know Solaris network stack implementation but I'll throw out my theory/explanation of why it should be safe.

    • Thread A enters some blocking system call, say read(2), for this given socket. There's no data in socket receive buffer, so thread A is taken off the processor an put onto wait queue for this socket. No network stack events are initiated here, connection state (assuming TCP) has not changed.
    • Thread B issues close(2) on the socket. While kernel socket structure should be locked while thread B is accessing it, no other thread is holding that lock (thread A released the lock when it was put to sleep-wait). Assuming there's no outstanding data in the socket send buffer, a FIN packet is sent and the connection enters the FIN WAIT 1 state (again I assume TCP here, see connection state diagram)
    • I'm guessing that socket connection state change would generate a wakeup for all threads blocked on given socket. That is thread A would enter a runnable state and discover that connection is closing. The wait might be re-entered if the other side has not sent its own FIN, or the system call would return with eof otherwise.

    In any case, internal kernel structures will be protected from inappropriate concurrent access. This does not mean it's a good idea to do socket I/O from multiple threads. I would advise to look into non-blocking sockets, state machines, and frameworks like libevent.

提交回复
热议问题