Skip to content
BytePatterns

Locks and Mutexes

Concurrency: lesson 3 of 10

One thread inside, everybody else waits.

Lesson 3 of 10 · 5 min

Locks and Mutexes

Step 1 of 10

A mutex is one token. Whoever holds it may touch the counter; everyone else waits.

The Idea

A mutex is a single token. A thread takes it before touching shared state and returns it after; anyone else asking must wait. The rule that makes it work is boring: every access to that state, without exception, goes through the same lock.

Real-World Example

A photo lab hangs one darkroom key on a hook by the door. You cannot open the door without it, so nobody can walk in and flood the room with light halfway through your print. The key on the hook means the room is free.

The Code

import threading

counter = 0
lock = threading.Lock()

def bump(times):
    global counter
    for _ in range(times):
        with lock:              # released automatically, even on error
            counter += 1

workers = [threading.Thread(target=bump, args=(50000,)) for _ in range(4)]
for w in workers: w.start()
for w in workers: w.join()
print(counter)                  # 200000, every single run

Your turn

Fill in the blank.

import threading

lock = threading.Lock()
total = 0

def add():
  global total
  for _ in range(10000):
      ___
          total += 1

ts = [threading.Thread(target=add) for _ in range(2)]
for t in ts: t.start()
for t in ts: t.join()
print(total)     # want 20000

Mini quiz

1 / 3

A mutex guarantees that a critical section is: