开发者

Pthreads dying in the middle of a mutex lock

I was thinking of the following scenario happening while a pthread is running:

pthread_mutex_lock(...);
... // <- Thread dies here
pthread_mutex_unlock(...);

in other words, a pthread starts, at some point it locks a mutex, and for some reason, it dies before it is able to call the matching unlock function, either because another thread killed it, or the O开发者_JS百科S itself (android in this case), decided it needed to kill it for some reason or other (it needed to do other things, etc.)

Would this ever happen on android (or any other OS really) without you invoking a pthread_kill() or something like that, and even if you did, what is the proper way to avoid just such a thing from happening? Thank you.


Killing threads is never very useful. (unless you can afford to SIGKILL/abort the whole process anyway).

Instead unwind the stack with an exception and use RAII. If your process/OS has become so unstable that random thread aborts happen, I think you'll have other worries and the resulting mess is not the process' responsibility.

Just Don't pthread_kill

Also, all of this might become slightly more interesting when using inter-process sync primitives. In that case, though, I think Linux kernels guarantee that any locks held by a process will be released when that process is terminated, whatever the cause


If the thread is really killed then I don't think that anything can help. (Don't kill your threads. Ever.)

But there is another possibility: May be your code generated exception that you didn't catch. If that is the case then you have to either: (1) catch all exceptions before unlock or much better (2) make a mutex locking guard class (since you tagged as C++) that locks the mutex in its constructor and unlocks in destructor and define the objects of this class in any scope you want to be mutex-locked (this is exception-safe approach) but it won't help if something kills the thread.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜