pthread_mutex_trylock detects deadlocks, doesn’t block, then why would you even “need” pthread_mutex_lock?
Perhaps when you deliberately want the thread to block? But in that case it may result in a deadlock?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
pthread_mutex_trylockdoes not detect deadlocks.You can use it to avoid deadlocks but you have to do that by wrapping your own code around it, effectively multiple calls to
pthread_mutex_trylockin a loop with a time-out, after which your thread releases all its resources.In any case, you can avoid deadlocks even with
pthread_mutex_lockif you just follow the simple rule that all threads allocate resources in the same order.You use
pthread_mutex_lockif you just want to efficiently wait until the resource is available, without having to spin on the mutex, something which is often very inefficient. Properly designed multi-threaded applications have no need for thepthread_mutex_trylockvariant.Locks should only be held for the absolute minimum time to do the work and, if that’s too long, you can generally redesign things so the lock time is less (such as by using the mutex to only copy data to a thread’s local data areas, and having the long-running bit work on that after the mutex is released).
The pseudo-code:
will continue to run your thread, waiting for the lock to be available, especially since there is no
pthread_yield()in POSIX threads (though it’s sometimes provided as a non-portable extension).That means, at worst, the code segment above won’t even be able to portably yield the CPU, therefore chewing up the rest of it’s quantum every time through the scheduler cycle.
And at best, it will still activate the thread once per scheduler cycle just to see if the mutex can be obtained.
Whereas:
will most likely totally pause your thread until the lock is made available, since it will move it to a waiting queue until the current lock holder releases the mutex.
That’s probably the major reason why you should prefer
pthread_mutex_locktopthread_mutex_trylock.