Deadlock with mutex locks

Deadlock can occur in multithreaded Pthread programs when multiple threads compete for mutex locks in conflicting orders. This happens when threads acquire locks in different sequences, potentially creating a circular dependency where each thread waits for resources held by others.

Mutex Lock Initialization

An unlocked mutex is initialized using the pthread_mutex_init() function. Threads acquire and release mutex locks using pthread_mutex_lock() and pthread_mutex_unlock() respectively. If a thread attempts to acquire an already locked mutex, the call to pthread_mutex_lock() blocks the thread until the owner releases the lock.

Example − Deadlock Scenario

Consider the following example where two mutex locks are created −

/* Create and initialize the mutex locks */
pthread_mutex_t mutex1;
pthread_mutex_t mutex2;
pthread_mutex_init(&mutex1, NULL);
pthread_mutex_init(&mutex2, NULL);

Two threads are created with access to both mutex locks. Thread1 and thread2 run in different functions with conflicting lock acquisition orders −

/* thread1 runs in this function */
void *dosomework_1(void *param) {
    pthread_mutex_lock(&mutex1);  // Acquire mutex1 first
    pthread_mutex_lock(&mutex2);  // Then mutex2
    
    /**
     * Do some work
     */
     
    pthread_mutex_unlock(&mutex2);
    pthread_mutex_unlock(&mutex1);
    pthread_exit(0);
}

/* thread2 runs in this function */
void *dosomework_2(void *param) {
    pthread_mutex_lock(&mutex2);  // Acquire mutex2 first
    pthread_mutex_lock(&mutex1);  // Then mutex1
    
    /**
     * Do some work
     */
     
    pthread_mutex_unlock(&mutex1);
    pthread_mutex_unlock(&mutex2);
    pthread_exit(0);
}

How Deadlock Occurs

Deadlock Scenario Thread 1 Thread 2 Mutex1 Mutex2 holds holds wants wants DEADLOCK! Each thread waits for the other's resource

In this example, deadlock occurs when −

  • Thread1 acquires mutex1 and then tries to acquire mutex2

  • Thread2 acquires mutex2 and then tries to acquire mutex1

  • Both threads become permanently blocked, waiting for each other to release their held resources

Key Points

Aspect Description
Lock Ordering Different acquisition sequences create potential for circular dependencies
Timing Dependency Deadlock occurs only under specific CPU scheduling circumstances
Detection Difficulty Hard to identify and test since it depends on thread execution timing
Prevention Consistent lock ordering across all threads prevents deadlock

Conclusion

Deadlock with mutex locks occurs when threads acquire locks in different orders, creating circular dependencies. While deadlock may not always occur due to timing variations, it represents a serious concurrency issue that requires careful design to prevent through consistent lock ordering strategies.

Updated on: 2026-03-17T09:01:38+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements