I am writing a program with a few critical sections. The thing is I need to check the value of a mutex in an if statement.
I would like to do something like this:
if pthread_mutex(&mutex) == 0 // locked
// Do something
else if pthread_mutex(&mutex) == 1 // unlocked
// Do something else
Is this possible?
You want pthread_mutex_trylock().
From that link:
The pthread_mutex_trylock() function shall be equivalent to pthread_mutex_lock(), except that if the mutex object referenced by mutex is currently locked (by any thread, including the current thread), the call shall return immediately. ... Return values ... The pthread_mutex_trylock() function shall return zero if a lock on the mutex object referenced by mutex is acquired. Otherwise, an error number is returned to indicate the error
So your code would go like this:
pthread_mutex_t *m = /* ... */;
if (pthread_mutex_trylock(m) == 0)
{
/* Success! This thread now owns the lock. */
}
else
{
/* Fail! This thread doesn't own the lock. Do something else... */
}
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