7a6 Subj : Re: pthreads: cancelling thread blocked on berkeley socket accept() To : comp.programming.threads From : Luke Dalessandro Date : Mon Sep 19 2005 06:57 pm Sergei Organov wrote: > David Hopwood writes: > > >>Luke Dalessandro wrote: >> >>>I have a thread running on a listen()->accept()->spawn_job()->listen() >>>loop on a socket (unix/berkeley). I have the socket set to block on the >>>accept(). spawn_job() dispatches a thread to handle the incoming request. >>> >>>When the application is shut down, I want to cancel the thread and >>>close() the socket. Is it appropriate to call pthread_cancel() on a >>>blocked thread? If I call pthread_cancel(listener) and then >>>pthread_join(listener) from the main (parent) thread, am I guaranteed >>>that it is safe to close() the socket? >> >>You should set a shared 'shouldExit' flag and close() the socket from the >>main thread. The listening thread will get an error from the accept(), and >>can then exit when it sees that 'shouldExit' is set. > > > I'm afraid async close() is asking for troubles. I'd suggest to call > shutdown() from main thread, then call close() when accept() returns > error. > > BTW, this also allows close() call to remain in the destructor. > > -- Sergei. Sergei, Ok, so you're saying that a thread blocking on an accept() will return with an error if another thread calls shutdown on the socket. So in my example I can use the following sequence: Thread* t; Socket* s; s->Shutdown(); // calls os socket shutdown(); // t gets an accept error: I use error to break my "while (true)" // accept loop, and the thread returns. t->Join(); // guaranteed to join because thread has returned delete s; delete t; // if not stack allocated This seems nicer in the sense that I don't need a shouldExit flag or anything. Thanks guys, Luke . 0