Multithreaded Programming Guide

Locking a Mutex Before a Specified Absolute Time

Use the pthread_mutex_timedlock(3C) function to attempt until a specified time to lock a mutex object.

This function works as the pthread_mutex_lock() function does, except that it does not block indefinitely. If the mutex is already locked, the calling thread is blocked until the mutex becomes available, but only until the timeout is reached. If the timeout occurs before the mutex becomes available, the function returns.

pthread_mutex_timedlock() Syntax

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

pthread_mutex_t mutex;
timestruct_t abs_timeout;
int ret;

ret = pthread_mutex_timedlock(&mutex,  &abs_timeout); 

pthread_mutex_timedlock() Return Values

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


EINVAL

Description:

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.

Description:

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

Description:

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.


ETIMEDOUT

Description:

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

See the discussion in pthread_mutex_lock Return Values.