Skip to content

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.

OperationWhenWhat it doesOther names
P(S)Before entering the critical sectionIf S is 0, wait; if S is 1 or more, decrease S by 1 and enterwait, acquire
V(S)When leaving the critical sectionIncrease S by 1 to return the resource, and wake up a waiting processsignal, release

This is how it is used.

text
P(S)
  --- critical section ---
V(S)

Written as pseudocode, P and V work like this.

text
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 spot

One 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.

StepWhat happensS
1A arrives first, runs P(S), sets S to 0, and enters the critical section0
2B arrives later and runs P(S), but S is 0, so it waits0
3A finishes the critical section and runs V(S)1
4B stops waiting, sets S to 0, and enters the critical section0

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 ​

KindRange of SUsed for
Binary semaphore0 or 1Letting only one in at a time
Counting semaphoreInteger 0 or greaterWhen 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.

python
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.

text
Max number of people in the room at once: 2
Time for all 6 to finish: about 0.3s

If 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.

python
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)
text
Expected: 4000
Actual: 4000

No 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.

ComparisonMutexBinary semaphore
OwnerYes. Only the thread that locked it can unlock itNo. Anyone can do V(S)
Main purposeProtecting a critical section (mutual exclusion)Mutual exclusion + sending "go ahead now" signals between threads
Allowed at once11 (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.

python
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()
text
Semaphore: fine even if another thread releases it
Owned lock: error if a non-owner thread releases it -> cannot release un-acquired lock

Because 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 section
  • turn: whose turn it is when both want to enter
python
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 hand

Running 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.

python
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 done

This 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 figureCode above
I want to enterflag[i] = True
It is not my turnturn = j (yield to the other)
The loop through the two diamondswhile flag[j] and turn == j (busy waiting)
critical sectionCritical section
I don't want to enterflag[i] = False

Flowchart of Peterson's algorithm: mark wanting to enter, yield the turn, wait until the condition holds, critical section, clear the mark

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.
python
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 ​

AlgorithmNumber of processesKey idea
Dekker2Raising a hand (flag) and taking turns (turn). If it's the other's turn, lower your hand and wait
Peterson2Yield to the other before entering
BakeryNIn 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 with statement, 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 ​

ConceptSummary for non-CS majors
Critical sectionCode that touches shared data. Only a set number may enter at once
SemaphoreA parking lot display that controls entry using the number of spaces left (S)
P / V operationsTake a spot when entering, return a spot when leaving
AtomicityP and V must each run in one go, without being interrupted
Counting semaphoreWhen there are several of the same resource, allows that many at once
MutexA restroom with only one key. Only the person who locked it can unlock it
Difference from a binary semaphoreA mutex has an owner; a semaphore can be released by anyone
Dekker / PetersonTwo processes decide the order by raising hands and yielding
Bakery algorithmEnter in order of smallest ticket number (works for N processes)