Using pthread_mutex_trylock
What you'll learn: How to attempt to lock a mutex without causing your thread to stop and wait if the resource is busy.
The Problem with Patient Waiting
Normally, when you call pthread_mutex_lock, your thread is like a person standing in line for a single-occupancy bathroom. If the door is locked, you stand there and wait. You can’t do anything else; you are "blocked" until the person inside leaves.
In systems programming, sometimes you don't have time to wait. You might have other tasks to perform, or you might want to try grabbing a different resource instead. This is where pthread_mutex_trylock comes in.
The Non-Blocking Approach
Think of pthread_mutex_trylock as walking up to the door, giving the handle a quick turn, and—if it doesn't open immediately—walking away to do something else rather than standing in the hallway.
When you call this function:
- If the mutex is unlocked, the thread locks it and the function returns
0. - If the mutex is already locked, the function does not wait. It immediately returns a specific error code (
EBUSY).
Implementation Example
Here is how you handle the "try" logic in C. Notice that we check the return value immediately to decide our next move.
#include <stdio.h>
#include <pthread.h>
#include <errno.h>
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
void* perform_task(void* arg) {
// Attempt to grab the lock
if (pthread_mutex_trylock(&lock) == 0) {
printf("Lock acquired! Updating shared resource...\n");
// Critical section here
pthread_mutex_unlock(&lock);
} else {
// The lock was busy (returned EBUSY)
printf("Resource busy. Performing background work instead.\n");
}
return NULL;
}
Why Use This?
The primary advantage is responsiveness. By using trylock, a thread can remain productive. For example, in a video game, if the thread responsible for rendering the UI can't access the game state because the physics engine is updating it, the UI thread shouldn't freeze. It can use trylock to see if the data is available; if not, it can skip the update for one frame or draw a loading icon instead of hanging the entire application.
It is also a powerful tool for avoiding deadlocks. If a thread cannot acquire all the locks it needs, it can use trylock to fail gracefully, release the locks it already holds, and try again later.
Key takeaway
pthread_mutex_trylock allows a thread to check a resource's availability and move on immediately if it is busy, preventing the thread from entering a blocked state.