I want to check if the mutex is free and not acquired.
I tried to use pthread_mutex_trylock(mutex_object);
But that return a 0
if mutex is acquired and -1
for error.
What if the mutex is not acquired? Does it return any value for it?
Although you can Lock() or Unlock() a mutex, you can't check whether it's locked.
If the mutex is already locked by another thread, the thread waits for the mutex to become available. The thread that has locked a mutex becomes its current owner and remains the owner until the same thread has unlocked it.
If the mutex is already locked, the calling thread shall block until the mutex becomes available. This operation shall return with the mutex object referenced by mutex in the locked state with the calling thread as its owner.
Using pthread_mutex_lock() and pthread_mutex_unlock() Mutex locks are acquired and released. If a thread try to acquire a locked mutex, the call to pthread_mutex_lock() blocks the thread until the owner of the mutex lock invokes pthread_mutex_unlock().
pthread_mutex_trylock
does not return "-1 for error". It returns an 'error' code from the possible values in errno.h
. One of these, EBUSY
, means that another thread already owns the lock. You should not observe any other error codes from pthread_mutex_trylock
unless you have serious bugs in your program.
Note that for recursive mutexes, a return value of 0 does not distinguish between the case where the mutex was previously unlocked, and the case where the calling thread already owned it. In any case, if pthread_mutex_trylock
returns 0, you're responsible for unlocking it via pthread_mutex_unlock
since you become the owner (or, in the recursive case, your lock count increases by 1) on successful pthread_mutex_trylock
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With