I read the Linux man page and OpenGroup for pthread_mutex_lock
and get this:
If successful, the pthread_mutex_lock() and pthread_mutex_unlock
In this context mutex is acquired means that there was no thread holding the lock at the time. If the mutex is recursive, the call to pthread_mutex_trylock()
will succeed unless it has been recursively locked too many times.
You can think of pthread_mutex_trylock()
as a non-blocking call, where if it would have blocked, it returns with an error instead. If it returns success, it means you have the lock as if pthred_mutex_lock()
returned successfully. If it fails with EBUSY
it means some other is holding the lock. If it fails with EOWNERDEAD
, the lock was held by another thread, but that thread had died (getting the lock actually succeeded, but the current data state may not be consistent). If it fails with EAGAIN
it was locked recursively too many times. There are other failure reasons, but in those cases, the lock has not been acquired.
int error = pthread_mutex_trylock(&lock);
if (error == 0) {
/*... have the lock */
pthread_mutex_unlock(&lock);
} else if (error == EBUSY) {
/*... failed to get the lock because another thread holds lock */
} else if (error == EOWNERDEAD) {
/*... got the lock, but the critical section state may not be consistent */
if (make_state_consistent_succeeds()) {
pthread_mutex_consistent(&lock);
/*... things are good now */
pthread_mutex_unlock(&lock);
} else {
/*... abort()? */
}
} else {
switch (error) {
case EAGAIN: /*... recursively locked too many times */
case EINVAL: /*... thread priority higher than mutex priority ceiling */
case ENOTRECOVERABLE:
/*... mutex suffered EOWNERDEAD, and is no longer consistent */
default:
/*...some other as yet undocumented failure reason */
}
}
The EAGAIN
, EINVAL
, ENOTRECOVERABLE
, and EOWNERDEAD
also happen with pthread_mutex_lock()
. For more information, consult the documentation and man page.