Mutex vs Semaphore Using a Gas Station Bathroom Analogy

gas_station_bathroom_key

Table of Contents

In this post, I will discuss the difference between a mutex and a semaphore using a gas station bathroom analogy.


What is a Mutex?

A mutex (mutual exclusion object) grants exclusive access to shared data or computer hardware. It is like a bathroom key at a gas station. If you have the key, nobody else can enter the bathroom while you are using it. Only one person (task) can use the bathroom (shared resource) at a time.

If a person (task) wants to use the bathroom, he or she must first get the bathroom key (mutex) since there is only one copy. The gas station owner (operating system) is responsible for managing the bathroom key (mutex).

Return to Table of Contents

What is a Semaphore?

Continuing from our example in the previous section, imagine that there are two bathrooms (shared resources) instead of one. Also there are two bathroom keys instead of one. Since bathroom entry is no longer exclusive, this is not a mutex scenario. Instead, the keys are called semaphores.

A semaphore enables two or more (two in this example) tasks (people) to use a shared resource (gas station bathroom) simultaneously.

  • If two keys (semaphores) are available, the value of the semaphore is 2.
  • If one key is available, the value of the semaphore is 1.
  • If no keys are available, that means that two tasks (people) are currently working (in the bathroom). The value of the semaphore is 0. The next task (person) must wait until a semaphore becomes available (i.e. a task finishes, and the semaphore is incremented by 1).

Return to Table of Contents

What Technique of Protecting Shared Data Requires Less Overhead?

Answer: Semaphore

Overhead includes things like memory, bandwidth, and task execution time. If tasks are able to work on different copies of shared data, each individual task will undoubtedly perform its function with less overhead. There is no waiting in line or waiting for a semaphore to be released.

However, the operating system (gas station owner) will have more overhead. It will spend a lot of resources having to manage the different copies of data. In addition, relative to a mutex implementation, copying data and enabling concurrent processing of that data will require more memory and processing power.

Return to Table of Contents