Subj : Re: close while read-ing To : comp.programming.threads From : David Schwartz Date : Tue May 24 2005 08:15 pm "Lyonya" wrote in message news:XuQke.870$So7.823@fe10.lga... > what might happen if one thread is blocked on a read() from a socket and > another thread tries to close() it? You must design your code so that can never, ever happen. There is no way the thread that is trying to close the socket can no for sure that the thread is blocked in read (as opposed to being *about* to call read). So you cannot write code that does what you suggest without invoking undefined (and extremely dangerous) behavior. For a TCP socket, you can unblock and terminate the connection by calling "shutdown". But you must not release a shared resource while another thread is or might be using it. If thread A does this: A1) close(s); and Thread B does this: B1) read(s); Your example assumes that A1 comes *after* B1. But since there's no synchronization (and no way to put any in, try it), you can also have A1 come *before* B1. Now imagine this, there's some other thread somewhere in the system that allocates a socket. Like this: C1) j=socket(); C2) bind(j); Now, what happens if you get A1, C1, C2, B1? You now have thread B reading on the wrong socket entirely, and thread C and its network connection will get completely screwed up. You will find that any design that allows what you suggest will also allow what I warn about. It is literally impossible to prevent it (without doing crazy things like suspending threads, finding out where they are, and so on). DS .