Multithreaded Programming Guide

Locking a Mutex Without Blocking

Use pthread_mutex_trylock(3C) to attempt to lock the mutex pointed to by mutex, and return immediately if the mutex is already locked.

pthread_mutex_trylock Syntax

int pthread_mutex_trylock(pthread_mutex_t *mutex); 
#include <pthread.h>

pthread_mutex_t mutex;
int ret;

ret = pthread_mutex_trylock(&mutex); /* try to lock the mutex */

pthread_mutex_trylock() is a nonblocking version of pthread_mutex_lock(). If the mutex object referenced by mutex is currently locked by any thread, including the current thread, the call returns immediately. Otherwise, the mutex is locked and the calling thread is the owner.

pthread_mutex_trylock Return Values

pthread_mutex_trylock() returns zero after completing successfully. Any other return value indicates that an error occurred. When any of the following conditions occurs, the function fails and returns the corresponding value.


EBUSY

Description:

The mutex could not be acquired because the mutex pointed to by mutex was already locked.


EAGAIN

Description:

The mutex could not be acquired because the maximum number of recursive locks for mutex has been exceeded.

If the symbol _POSIX_THREAD_PRIO_INHERIT is defined, the mutex is initialized with the protocol attribute value PTHREAD_PRIO_INHERIT . Additionally, if the robustness argument of pthread_mutexattr_setrobust_np() is PTHREAD_MUTEX_ROBUST_NP, the function fails and returns one of the following values:


EOWNERDEAD

Description:

See the discussion in pthread_mutex_lock Return Values.


ENOTRECOVERABLE

Description:

See the discussion in pthread_mutex_lock Return Values.


ENOMEM

Description:

The limit on the number of simultaneously held mutexes has been exceeded.