This is the mail archive of the
libc-help@sourceware.org
mailing list for the glibc project.
Re: Avoiding deadlock with mutex trylock in multithreaded app.
Le samedi 8 août 2009 17:24:15 Pierre Mallard, vous avez écrit :
> I have a question regarding proper handling of non concurrent access
> between two (or more) thread that deals together on a
> register/unregister + callback way.
Generally speaking you should avoid holding locks while entering a callback.
Copy the callback parameters to the stack, release your lock, invoke the
callback, and acquire your lock again. Alternatively, use a recursive lock.
Eithe way, be careful that the lock-protected state might have changed in the
mean time.
(...)
> I am wondering whether the trylock approach is the good one, and also
> how could I avoid the waste of time (and CPU !) trying to lock mutex_B
> ?
Neither of them are good.
> "The deadlock way"
> A Module A mutex between callback calls and unregister function, to
> check if request is still existing,
> A Module B mutex between release and callback.
> But that leads to a dead lock :
Yes.
> "The TryLock way"
> I can Trylock instead of lock in Callback, Therefore, when release is
> called and lock mutex_B, callback won't hold mutex_A if it realize
> mutex_B is busy.
So, trylock fails... What do you do? Maybe it's failing because you are in the
cleanup phase. But maybe it's just that some other thread has the lock for
another reason. Since you did not get the lock, you cannot read the protected
state, so you cannot check why you did not get the lock...
By the way, your code is buggy. If thread cancellation is acted upon from
within fprintf() or from within the callback, the lock will stale.
--
Rémi Denis-Courmont
http://www.remlab.net/