Course contentsShow
← Computer Science
Lesson 1288 of 2,87230. Process SynchronizationFree lesson

Recursive Locks (Reentrant Mutexes)

Understanding recursive mutexes that allow the same thread to acquire the lock multiple times without deadlock.

Recursive Locks (Reentrant Mutexes)

You'll learn how a special kind of mutex allows the same thread to lock it multiple times without getting stuck.

The Problem with Regular Mutexes

So far, you've worked with standard mutexes where a thread acquires a lock, enters its critical section, and releases it. But what happens if that same thread tries to lock the same mutex again before releasing it? With a regular mutex, the thread deadlocks—it blocks waiting for itself to release the lock, which will never happen!

This scenario arises naturally when you have nested function calls or recursive algorithms where each function needs to acquire the same lock.

What is a Recursive Lock?

A recursive lock (also called a reentrant mutex) keeps track of which thread owns it and how many times that thread has locked it. The same thread can acquire the lock multiple times without blocking. The lock is only truly released when the thread has called unlock the same number of times it called lock.

Analogy

Imagine a diary with a combination lock. A regular lock means once you open it, you can't "open" it again until you close it. A recursive lock is like a diary that remembers you opened it, so you can flip it open multiple times while reading—but you must close it the same number of times before anyone else can use it.

Key Behavior

  • Owner tracking: The mutex remembers which thread holds it
  • Lock count: Increments on each lock, decrements on each unlock
  • Release condition: Only released when count reaches zero
  • Same-thread only: Only the owning thread can lock it multiple times

Key Takeaway: Recursive locks prevent self-deadlock by allowing the same thread to acquire the lock multiple times, tracking a lock count that must return to zero before the mutex is truly released.