Subj : Re: How to guarantee no stale mutexes, ever? To : comp.programming.threads From : David Schwartz Date : Thu Aug 11 2005 02:50 pm "Damon Hastings" wrote in message news:1123788695.743824.182390@g14g2000cwa.googlegroups.com... > 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. What does "threads dying" mean? > 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. Exactly. > But are there other ways a thread can die without rewinding the stack? > Can they sometimes simply vanish? Only if something awful happens to the process as a whole. There is no isolation between threads. > 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? POSIX provides no way to terminate a thread that doesn't invoke the cleanup handlers. > 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 That's essentially impossible to do correctly. If thread A dies and thread B blocks on a mutex it held, there is nothing you can do to unwedge things really. DS .