Mutex ensures that only one thread can access the shared resource at a time. It provides exclusive ownership and is typically used for protecting critical sections of the code.
Semaphore can control access to a resource by multiple threads simultaneously. It allows a specified number of threads to access the resource, often used for scenarios like managing thread concurrency.
In summary, mutex is used for exclusive access, while a semaphore can limit access to a shared resource to a specified number of threads.
Let us consider an example to understand it better...
Imagine a library with a study room that can accommodate only one student at a time. The library has a key that allows access to this study room.
Student 'A' wants to study in the room. Student 'A' takes the key, enter, and lock the door. While inside, no other student can enter. Only when Student 'A' finishes and leaves the room then Student 'B' get the key and access the room.
In this case, the mutex (the key) ensures exclusive access to the study room.
Now, consider a different scenario in the same library, where the study room can accommodate up to three students at once, but no more.
There's a sign outside the room that says, "Maximum occupancy: 3." Students who want to study in the room can check the sign. If there are already three students inside, they must wait until one student leaves. When someone exits the room, a waiting student can enter.
In this case, the semaphore (the sign indicating occupancy) controls access by allowing a specified number of students to enter the room concurrently.
Conclusion: The mutex ensures exclusive access like having a key to the study room, while the semaphore controls access by limiting the number of students in the room, just like the occupancy limit on the sign.