Subj : How to guarantee no stale mutexes, ever? To : comp.programming.threads From : Damon Hastings Date : Thu Aug 11 2005 01:31 pm Hi there, I'm writing a generic threadpool, and I use mutexes in various places. I'm worried about threads dying while holding mutexes. Now, the threadpool code only holds mutexes very briefly, but still, I'd rather it were absolutely bulletproof even in cases of high contention. I always wrap each mutex in a wrapper object which will automatically unlock it when the wrapper destructs (the RAII idiom) -- and I allocate the wrapper object on the stack so that it must eventually destruct even if an exception is thrown. But is that good enough? It occurs to me that I don't know all the ways in which a thread might terminate without even rewinding the stack. I know of these ways: - pthread_cancel(), pthread_exit() *Might* bypass the stack rewind -- can use cleanup handlers in that case. - exit(), abort(), signal death Should kill entire process, so mutex becomes irrelevant. But are there other ways a thread can die without rewinding the stack? Can they sometimes simply vanish? I'd like for my implementation to provide a bulletproof guarantee that either cleanup will happen or the entire process will die. But the man page for the cleanup handlers just says "Cleanup handlers are functions that get called when a thread terminates, either by calling pthread_exit(3) or because of cancellation." That wording seems to imply there might be cases when the handlers aren't called... Does POSIX provide any guarantees here? If the cleanup handlers aren't guaranteed, then I'll have to maintain a global mutex registry and run a sweeper thread to clean it periodically, and that's just a big horking mess for reasons I won't go into. :-P Thanks for any advice, Damon P.S. I'm using C++ (gcc-2.95.3) with LinuxThreads pthreads on Linux kernel 2.4 running on a P4. Though of course I'd prefer a cross-platform portable solution. :) .