using pthread_mutex_timedlock in linux.

We saw in the post " " how we can use mutexes in pthreads to achieve synchronization among various threads. Along with the the three functions we saw, there is a fourth mutex function that we can use when we want to wait on a mutex for only a specific duration and then continue irrespective of whether we are able to get a lock on the mutex or not. The function for timed operation on mutex it pthread_mutex_timedlock whose syntax is

The timeout is the time for which we want to wait on the mutex. To specify the timeout we need to use the structure timepsec which has two fields one for seconds and other for nanoseconds as shown below.

The mutex if available will be locked immediately, if the mutex is not available the thread will wait for the duration of time mentioned in the abs_timeout and then exit from the wait.

The following program shows an example of using the pthread_mutex_timedlock. In the program thread1 takes a value as input from the user and assigns it to a variable "temp". In thread2 the same variable is accessed and its value is printed. Thread1 locks a mutex while getting the value for temp from the user, but thread2 waits only for 5 seconds for the mutex to get unlocked after which it exits with a time out message and does not print the value of the variable temp.

To mention the timeout we need to first allocate memory for a timespec structure

Thus now we have a timespec structure with 5 seconds and 0 nanoseconds as the time values, which can be passed to the function pthread_mutex_timedlock to achieve a 5 second timeout.
The whole function looks as follows

Save the program as mutex_timedlock.c, and compile it with the flag -lpthread

While executing the program when the prompt for entering a value for the variable appears, if you wait for more than 5 seonds for entering the value, you will noticed the timed out message from the second thread will appear on the other hand if we enter the value with in 5 seconds the value entered is printed by the second thread. case1: Waiting for more than 5 seconds before entering the value

Thus we are able to achieve a mutex lock for a specific duration using the pthread_mutex_timedlock function.


  1. what is the reason of

    1. The sleep(5) is to make sure that the first thread,func1, always gets the lock first. If the second thread gets the lock first, the example will not work as desired.

  2. I think it should be:

    wait=(struct timespec *)(malloc(sizeof(struct timespec)));

    1. That would also work, but am not sure if gettimofday is really required here. The code seems to work fine without it too.


Follow by Email