#13: Mutex vs. Semaphore
Hello! Today, let’s explore the differences between mutexes and semaphores.
Let’s discuss two of the most common synchronization mechanisms in programming: mutexes and semaphores. Although they may seem similar, mutexes and semaphores serve different purposes and are used in distinct scenarios to manage shared resources.
A mutex (short for mutual exclusion) is a locking mechanism that ensures only one thread can access a specific resource or section of code at a time. If another thread tries to access it while it's locked, that thread has to wait until the mutex is unlocked.
How it works: When a thread wants to access a resource, it attempts to lock the mutex. If it succeeds, the thread can proceed. Once the thread is finished with the resource, it unlocks the mutex, allowing other threads to take over.
Example: Imagine a room with a key. If one person (thread) has the key (mutex), they can enter the room (access the resource). Others have to wait outside until that person leaves and returns the key (unlocks the mutex).
A semaphore is a signaling mechanism that controls access to a pool of resources. It keeps track of a count, which represents the number of available resources. Unlike a mutex, semaphores can allow multiple threads to access resources simultaneously, up to a limit.
How it works: When a thread wants to use a resource, it checks the semaphore’s count. If the count is greater than zero, the thread can proceed, and the count is decremented (one resource is taken). Once the thread is finished, it increments the count, signaling that a resource is available again.
Example: Think of a parking lot with limited spaces. If there are five spaces (resources), each car (thread) can take a spot until the lot is full (count is zero). Once a car leaves, a spot opens up, and another car can take it.
The key differences:
Capacity:
Mutex: Only one thread can hold the lock at a time.
Semaphore: Controls access to multiple resources.
Semantic:
Mutex: It’s a locking/unlocking mechanism.
Semaphore: It’s a signaling mechanism.
Ownership:
Mutex: The thread that locks the mutex is responsible for unlocking it.
Semaphore: There’s no strict ownership; any thread can increase or decrease the count.
In simpler terms:
A mutex conveys: “I’m using this resource; no one else can use it until I’m done”.
A semaphore conveys: “There are this many resources available; take one if you need it, and let others know when you’re done”.
Tomorrow, we will keep discussing fundamental concurrency concepts, but this time between data races and race conditions.