tags:

views:

68

answers:

2

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 same socket, will the thread in the recv call know this and come out safely?

I would like to know if the behavior will differ between different OS / Platforms. If yes, how will it behave in Solaris?

+1  A: 

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.

Nikolai N Fetissov
A: 

Yes, it is ok to close the socket from another thread. Any blocked/busy threads that are using that socket will report a suitable error.

Remy Lebeau - TeamB
In linux atleast it doesn't seem to reporting like that. A blocked recv thread remains blocked, even if we call close from another thread.
Jay