Updated: April 19, 2023 |
Lock a mutex, with a time limit
#include <pthread.h> #include <time.h> int pthread_mutex_timedlock( pthread_mutex_t * mutex, const struct timespec * abs_timeout ); int pthread_mutex_timedlock_monotonic( pthread_mutex_t * mutex, const struct timespec * abs_timeout );
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.
The pthread_mutex_timedlock() function locks the mutex object referenced by mutex. If the mutex is already locked, the calling thread blocks until the mutex becomes available as in the pthread_mutex_lock() function. If the mutex can't be locked without waiting for another thread to unlock the mutex, the wait is terminated when the specified timeout expires.
The pthread_mutex_timedlock_monotonic() function is a QNX Neutrino extension; it's similar to pthread_mutex_timedlock(), but it uses CLOCK_MONOTONIC, so the timeout isn't affected by changes to the system time.
If you want to choose the clock against which the timeout is measured, you can instead use pthread_mutex_clocklock(), which is similar to pthread_mutex_timedlock() and pthread_mutex_timedlock_monotonic() and differs only because of its clock parameter (clk). Choosing the clock prevents the timeout from being affected by changes to the system time.
By default, if a thread with a higher priority than the mutex owner attempts to lock a mutex, then the effective priority of the current owner is increased to that of the higher-priority blocked thread waiting for the mutex. The owner returns to its real priority when it unlocks the mutex. For more information, see Mutexes: mutual exclusion locks in the QNX Neutrino Microkernel chapter of the System Architecture guide.
The timeout expires when the absolute time specified by abs_timeout passes, as measured by the clock on which timeouts are based (i.e., when the value of that clock equals or exceeds abs_timeout), or if the absolute time specified by abs_timeout has already been passed at the time of the call.
The timeout is based on the CLOCK_REALTIME clock. The timespec datatype is defined in the <time.h> header.
If the mutex can be locked immediately, the validity of the abs_timeout parameter isn't checked, and the function won't fail with a timeout.
As a consequence of the priority inheritance rules (for mutexes initialized with the PTHREAD_PRIO_INHERIT protocol), if a timed mutex wait is terminated because its timeout expires, the priority of the owner of the mutex is adjusted as necessary to reflect the fact that this thread is no longer among the threads waiting for the mutex.
pthread_mutex_timedlock() is POSIX 1003.1; pthread_mutex_timedlock_monotonic() is QNX Neutrino
Safety: | |
---|---|
Cancellation point | No |
Interrupt handler | No |
Signal handler | No |
Thread | Yes |