Skip to content
BENIBIX Learn

Mutex (Lock)

Development⚙️ Compilers & RuntimesConcurrency

Also known as Mutex, Lock, Mutual Exclusion

A lock that lets only one thread at a time touch shared data.

Think of it like

Think of it like the key to a toilet for one. Only the person with the key can go in.

Example

Lucy has two threads that each add 1 to a counter 100,000 times. With a lock around the add, the total is always 200,000.

Why it matters

It is the basic tool to keep shared data right when many threads run at once.

Definition

A mutex is a lock that lets only one thread at a time into a piece of code. The name is short for mutual exclusion. A thread takes the lock before touching shared data. Any other thread that wants it has to wait. When the first thread is done, it lets go and the next one goes in. This stops race conditions, but holding locks too long makes a program slow.

Example code

python
lock = threading.Lock()

def add():
    global count
    for _ in range(100000):
        with lock:        # one thread at a time
            count += 1
Run this in two threads and the count ends at 200,000 every time.

Common mistake

Taking two locks in a different order in different places. Two threads can then wait on each other forever.

Key takeaways

  1. 1
    One at a time. Others wait their turn.
  2. 2
    Take, then release. Always let go.
  3. 3
    Hold it briefly. Long locks slow everyone.