Search

Using pthread_mutex_trylock

In the mutex we saw in the post " " , if a mutex is locked by one thread, other threads will wait infinitesly for the mutex when pthread_mutex_lock is called. The other threads wil get out pf hte wait only when the mutex becomes available or the process is killed.
If such a behviour of infinite wait is undesirable we can use the variant pthread_mutex_trylock.

In this function the thread will try to lock the mutex, but in case the mutes in not available, it will return with an error EBUSY and will not try to acuire the lock again . If it is able to lock the mutex, the return value is 0 else it returns a non zero error value.

The following code shows the use of the function pthread_mutex_trylock. In the program, two threads are created one to write to a file and another to read from the file. The read thread is started with a little delay to allow the write thread to get access of the mutex.

Both the thread lock the muetx using pthread_mutex_trylock. The write thread is able to get access to the lock and continues with the execution of the thread. The read thread on the other hand tries to access the lock but is unaalbe to get a lock on the mutex as the write thread is holding the same. Thus it returns with an error value, because of which the thread has to be exited with our reading the file.



Save the file as mutex_trylock.c, and compile it using the flab -lpthread



We can see from the messages that the read thread has returned with an error and was unable to open the file as the pthread_mutex_trylock failed to get the lock.


Follow by Email