Semaphore & Mutex
Semaphores and mutexes are tools that control entry so that multiple processes or threads cannot access a shared resource at the same time. Think of them as gatekeepers standing in front of a critical section to prevent a race condition.
At a Glance
- Analogy: a mutex is the single key to a restroom. Only the person holding the key can go in, and when finished, that same person returns the key.
- A semaphore is the "spaces left" display board at a parking lot entrance. If there are 3 spaces, up to 3 cars can enter; when it hits 0, the next car waits until a space opens up. When a car leaves, the number goes back up.
- In short, a mutex allows "exactly one," and a semaphore allows "a fixed number."
Critical Section
When multiple processes run while sharing data, the part of each process's code that accesses the shared data is called the critical section. If several run this part at the same time, the result can be wrong, so while one process is executing its critical section, the others must be kept out.
A correct solution to the critical section problem must satisfy three conditions: mutual exclusion, progress, and bounded waiting. The meaning of each condition is explained in the Race Condition article.
Semaphore
A semaphore is a way of managing how many parties may access a shared resource at once, using a single integer (S). It was invented by the Dutch computer scientist Dijkstra.
P and V Operations
A semaphore is handled with only two operations.
| Operation | When | What it does | Other names |
|---|---|---|---|
| P(S) | Before entering the critical section | If S is 0, wait; if S is 1 or more, decrease S by 1 and enter | wait, acquire |
| V(S) | When leaving the critical section | Increase S by 1 to return the resource, and wake up a waiting process | signal, release |
This is how it is used.
P(S)
--- critical section ---
V(S)Written as pseudocode, P and V work like this.
procedure P(S) # assume S starts at 1
while S == 0: # if S is 0, wait until it becomes 1
wait
S = S - 1 # set S to 0 so other processes cannot enter
--- critical section ---
procedure V(S) # S is now 0
S = S + 1 # set S back to 1 to free the spotOne point here is important. P and V must each run in one go without being interrupted midway (atomic). If two processes both check "S is 1" at the same time and then both decrease S, both end up inside the critical section. So the operating system blocks interrupts while running P and V, or uses atomic instructions provided by the CPU, to guarantee these two operations are never split apart.
Walking Through an Example
Suppose S starts at 1, and there are processes A and B that want to run the same critical section.
| Step | What happens | S |
|---|---|---|
| 1 | A arrives first, runs P(S), sets S to 0, and enters the critical section | 0 |
| 2 | B arrives later and runs P(S), but S is 0, so it waits | 0 |
| 3 | A finishes the critical section and runs V(S) | 1 |
| 4 | B stops waiting, sets S to 0, and enters the critical section | 0 |
Busy Waiting vs. Blocking
Looping with while and checking S over and over, as in the pseudocode above, is called busy waiting, or a spinlock. It keeps using the CPU even while waiting, which is wasteful.
So semaphores in real operating systems usually put the waiting process in a wait queue and put it to sleep (block). Then, when V runs, one process is taken out of the queue and woken up (wakeup). When the wait is expected to be very short, spinning briefly is cheaper than the cost of sleeping and waking, so spinlocks are still used on multiprocessors.
Two Kinds of Semaphores
| Kind | Range of S | Used for |
|---|---|---|
| Binary semaphore | 0 or 1 | Letting only one in at a time |
| Counting semaphore | Integer 0 or greater | When there are several of the same resource (e.g. 5 DB connections, 3 printers) |
In Code: A Counting Semaphore
Six guests try to enter a room with 2 seats. Each stays for 0.1 seconds.
import threading
import time
seats = threading.Semaphore(2) # a room that allows at most 2 people at once (S = 2)
inside = 0
max_inside = 0
count_lock = threading.Lock()
def visitor(name):
global inside, max_inside
with seats: # P(S): wait here if there is no seat
with count_lock:
inside += 1
max_inside = max(max_inside, inside)
time.sleep(0.1) # time spent working inside the room
with count_lock:
inside -= 1
# leaving the block means V(S): seat returned
start = time.time()
threads = [threading.Thread(target=visitor, args=(f"Guest{i}",)) for i in range(6)]
for t in threads:
t.start()
for t in threads:
t.join()
print("Max number of people in the room at once:", max_inside)
print(f"Time for all 6 to finish: about {time.time() - start:.1f}s")Here is the output.
Max number of people in the room at once: 2
Time for all 6 to finish: about 0.3sIf all 6 had gone in at once, it would have taken 0.1 seconds; one at a time, 0.6 seconds. They went in 2 at a time in three rounds, so it took 0.3 seconds.
Mutex
A mutex is a technique that makes threads with a critical section run alone, without their execution times overlapping. The name is short for Mutual Exclusion.
It coordinates access with two actions.
- lock: obtains permission to enter the critical section. If another thread is already running the critical section, it waits until that thread finishes.
- unlock: announces that it is done with the critical section, so another waiting thread can enter.
In Code: Fixing the Race Condition
This is the example from the Race Condition article that should have printed 4,000 but printed around 1,000, with only a lock added.
import threading
import time
balance = 0
lock = threading.Lock() # mutex: only one thread passes at a time
def deposit(times):
global balance
for _ in range(times):
with lock: # lock() ... automatically unlock() when the block ends
current = balance # ---- start of critical section ----
time.sleep(0)
balance = current + 1 # ---- end of critical section ----
threads = [threading.Thread(target=deposit, args=(1000,)) for _ in range(4)]
for t in threads:
t.start()
for t in threads:
t.join()
print("Expected: 4000")
print("Actual:", balance)Expected: 4000
Actual: 4000No matter how many times you run it, it always prints 4,000. With with lock:, the lock is released automatically even if an error occurs midway, which prevents the mistake of leaving without releasing the lock.
Mutex vs. Binary Semaphore
A mutex has only two states, locked and unlocked, so it is sometimes called a binary semaphore. Strictly speaking, though, there is an important difference.
| Comparison | Mutex | Binary semaphore |
|---|---|---|
| Owner | Yes. Only the thread that locked it can unlock it | No. Anyone can do V(S) |
| Main purpose | Protecting a critical section (mutual exclusion) | Mutual exclusion + sending "go ahead now" signals between threads |
| Allowed at once | 1 | 1 (a counting semaphore allows several) |
Let's check the "has an owner" difference in code. Python's threading.Lock is a simple lock that does not check ownership, so RLock, which remembers its owner, is used here.
import threading
owned = threading.RLock() # a lock that remembers its owner (the thread that locked it)
sem = threading.Semaphore(1) # binary semaphore (value is 0 or 1)
owned.acquire() # main thread locks it
sem.acquire() # main thread sets S from 1 -> 0
def other_thread():
sem.release() # another thread does V(S)
print("Semaphore: fine even if another thread releases it")
try:
owned.release() # another thread tries to release someone else's lock
except RuntimeError as e:
print("Owned lock: error if a non-owner thread releases it ->", e)
t = threading.Thread(target=other_thread)
t.start()
t.join()Semaphore: fine even if another thread releases it
Owned lock: error if a non-owner thread releases it -> cannot release un-acquired lockBecause a semaphore has no owner, it can also be used as a signal to coordinate order between different threads, such as "the producer thread does V after creating data, and the consumer thread waits with P." A mutex must be released by whoever locked it, so it does not fit this use.
Mutex Algorithms
There are classic algorithms that build mutual exclusion using only shared variables, without help from the operating system or hardware. They are rarely used in practice, but often appear as textbook examples for understanding "how mutual exclusion is guaranteed."
All the code below has been rewritten in Python and actually run, repeatedly adding 1 inside the critical section. (Thanks to the GIL, Python guarantees the order of memory reads and writes, so these algorithms work as is. If you run them in C or Java on a multicore machine, the CPU may reorder instructions, so you need extra measures such as memory barriers or volatile.)
1. Dekker's Algorithm
For two processes. Two variables, flag and turn, decide who enters the critical section.
flag[i]: whether process i wants to enter the critical sectionturn: whose turn it is when both want to enter
flag = [False, False]
turn = 0
def worker(i, times):
global turn
j = 1 - i # the other process's number
for _ in range(times):
flag[i] = True # raise a hand to say "I want to enter"
while flag[j]: # if the other also has a hand raised
if turn == j: # and it's the other's turn
flag[i] = False # lower my hand for now
while turn == j: # wait until it's my turn
pass
flag[i] = True # raise my hand again
# ------- critical section -------
turn = j # hand the turn to the other
flag[i] = False # lower my handRunning two threads that each add 1,000 times printed 2000 every time.
2. Peterson's Algorithm
Similar to Dekker's, but simpler. The difference is that before entering, a process first yields the turn to the other. If both yield at the same time, whichever yielded last is what remains in turn, so the one that yielded first gets to enter.
flag = [False, False]
turn = 0
def worker(i, times):
global turn
j = 1 - i
for _ in range(times):
flag[i] = True # mark that I want to enter
turn = j # yield: "you go first"
while flag[j] and turn == j: # wait if the other wants in and it's their turn
pass
# ------- critical section -------
flag[i] = False # announce that I'm doneThis one also printed 2000 every time with two threads adding 1,000 times each.
Below is a flowchart of Peterson's algorithm from the point of view of one process. Matched line by line with the code above:
| Box in the figure | Code above |
|---|---|
| I want to enter | flag[i] = True |
| It is not my turn | turn = j (yield to the other) |
| The loop through the two diamonds | while flag[j] and turn == j (busy waiting) |
| critical section | Critical section |
| I don't want to enter | flag[i] = False |

Image source: Wikimedia Commons (Lpandelis, CC BY-SA 4.0)
3. Bakery Algorithm
This works like taking a number ticket at a bakery. It can handle many processes (N), and the process holding the smallest ticket number enters the critical section first.
- If two processes take tickets at the same moment, they may get the same number. In that case, the one with the smaller process number goes first.
- If some process is in the middle of taking a ticket, a process waits until that number is decided before comparing.
N = 3
choosing = [False] * N # whether each process is taking a ticket
number = [0] * N # ticket number (0 means not trying to enter)
def worker(i, times):
for _ in range(times):
choosing[i] = True
number[i] = max(number) + 1 # largest current number + 1
choosing[i] = False
for j in range(N):
while choosing[j]: # wait if j is taking a ticket
pass
# wait if j has a ticket and its (number, process number) is smaller than mine
while number[j] != 0 and (number[j], j) < (number[i], i):
pass
# ------- critical section -------
number[i] = 0 # return the ticket(number[j], j) < (number[i], i) checks in one expression "is the ticket number smaller, or, if the tickets are equal, is the process number smaller?" Running 3 threads that each add 500 times printed 1500 every time.
Comparing the Three Algorithms
| Algorithm | Number of processes | Key idea |
|---|---|---|
| Dekker | 2 | Raising a hand (flag) and taking turns (turn). If it's the other's turn, lower your hand and wait |
| Peterson | 2 | Yield to the other before entering |
| Bakery | N | In order of smallest ticket; if equal, in order of process number |
Things to Watch Out For
- If you acquire several locks or semaphores in the wrong order, you can get a deadlock, where everything stops while waiting on each other.
- If you do P and forget V, the spot is never returned and other processes wait forever. Using syntax that releases automatically, like Python's
withstatement, is safer. - If a lock covers too much, even many threads end up effectively working in a single line, which is slow. Keep the critical section short and only as large as it needs to be.
Summary
| Concept | Summary for non-CS majors |
|---|---|
| Critical section | Code that touches shared data. Only a set number may enter at once |
| Semaphore | A parking lot display that controls entry using the number of spaces left (S) |
| P / V operations | Take a spot when entering, return a spot when leaving |
| Atomicity | P and V must each run in one go, without being interrupted |
| Counting semaphore | When there are several of the same resource, allows that many at once |
| Mutex | A restroom with only one key. Only the person who locked it can unlock it |
| Difference from a binary semaphore | A mutex has an owner; a semaphore can be released by anyone |
| Dekker / Peterson | Two processes decide the order by raising hands and yielding |
| Bakery algorithm | Enter in order of smallest ticket number (works for N processes) |
