Multithreaded Programming Guide

Locking a Mutex Within a Specified Time Interval

Use the pthread_mutex_reltimedlock_np(3C) function to attempt until a specified amount of time elapses to lock a mutex object.

The timeout expires when the time interval specified by rel_timeout passes, as measured by the CLOCK_REALTIME clock, or if the time interval specified by rel_timeout is negative at the time of the call.

pthread_mutex_reltimedlock_np() Syntax

int  pthread_mutex_reltimedlock_np(pthread_mutex_t *restrict mutex, 
          const struct timespec *restrict rel_timeout);
#include <pthread.h>
#include <time.h>

pthread_mutex_t mutex;
timestruct_t rel_timeout;
int ret;

ret = pthread_mutex_reltimedlock_np(&mutex,  &rel_timeout); 

pthread_mutex_reltimedlock_np() Return Values

The pthread_mutex_reltimedlock_np() function returns 0 if it locks the mutex successfully. Otherwise, an error number is returned to indicate the error.



The mutex was created with the protocol attribute having the value PTHREAD_PRIO_PROTECT and the calling thread's priority is higher than the mutex's current priority ceiling.


The value specified by mutex does not refer to an initialized mutex object.


The process or thread would have blocked, and the abs_timeout parameter specified a nanoseconds field value less than 0 or greater than or equal to 1000 million.



The mutex could not be locked before the specified timeout expired.

See the discussion in pthread_mutex_lock Return Values.