October 2018
Beginner
794 pages
19h 23m
English
In certain situations, the developer might be tempted to ask: given a mutex, can I find out if it's in the locked or unlocked state? Perhaps the reasoning is: if locked, let's unlock it.
There is a way to test this: with the pthread_mutex_trylock(3) API. If it returns EBUSY, it implies that the mutex is currently locked (otherwise, it should return 0, implying it's unlocked). But wait! There is an inherent race condition here; just think about this:
if (pthread_mutex_trylock(&mylock) != EBUSY)) { <-- time t1 // it's unlocked <-- time t2}// it's locked
By the time we reach time t2, there is no guarantee that another thread has not, by now, locked the mutex in question! So, this approach is incorrect. (The only realistic ...
Read now
Unlock full access