Grokking Multithreading and Concurrency for Coding Interviews
Vote

0% completed

​

Mutex Lock

Know the Vocabulary

Part 1: The Last Seat Problem

How One Seat Gets Sold Twice

Why Testing Misses It

Part 2: What a Mutex Is

The Definition

What a Mutex Is Not

Part 3: Fixing the Ticket Sale

The Code

What the Mutex Changes, Step by Step

The Cost of Being Correct

Part 4: Always Unlock the Mutex

Part 5: What Goes Inside the Lock

Part 6: Common Mistakes

Mistake 1: Locking Only the Writes

Mistake 2: Each Thread Uses Its Own Mutex

Mistake 3: Locking the Same Mutex Twice

Mistake 4: Holding the Lock During Slow Work

Mistake 5: Two Mutexes in Opposite Order

Part 7: How a Mutex Works Inside

Part 8: Mutex or Another Tool?

FAQs

Key Takeaways

Check Your Understanding

Know the Vocabulary

This lesson uses the terms below many times. Read them once now, and come back here when a later section needs one.

  • Thread: One path of work inside a program. A program can run many threads at the same time.
  • Shared data: Data that more than one thread can read or change, such as a count of seats left.
  • Race condition: A bug where the result depends on which thread happens to run first.
  • Critical section: The part of the code that uses shared data and must run in only one thread at a time.
  • Mutex: A lock that only one thread can hold at a time. The name comes from "mutual exclusion."
  • Lock (verb): To take the mutex. A thread that locks a mutex is said to acquire it.
  • Unlock (verb): To give the mutex back so that another thread can take it. This is also called releasing it.
  • Owner: The thread that holds the mutex right now.
  • Blocked: The state of a thread that is waiting for a mutex that another thread holds.
  • Deadlock: A state where two or more threads each wait for a lock that another one holds, so none of them can ever continue.
  • Atomic operation: An operation that the hardware finishes in one step, so no other thread can see it half done.

Part 1: The Last Seat Problem

A band announces a concert, and the ticket sale opens at 10:00. At that moment, 10 seats are left and 20 fans click "Buy" at the same time. The ticket website handles each click on its own thread, so 20 threads run the same booking code together.

The booking code is short. It checks whether a seat is left, reserves the seat, and then lowers the count:

if seats_left > 0: # 1. check reserve_seat() # 2. reserve (takes about 20 ms) seats_left -= 1 # 3. update tickets_sold += 1

Run by one thread, this code is correct. Run by 20 threads at the same time, it sells seats that do not exist.

How One Seat Gets Sold Twice

Picture the very last seat, with two buyers, Thread A and Thread B. The steps below show one way their work can mix together.

Step 1: Thread A checks. Thread A reads seats_left and sees 1. One seat is left, so Thread A moves on to reserve it.

Step 2: Thread B checks. Thread A has not changed the count yet. Thread B also reads 1, so Thread B also moves on.

Step 3: Both threads reserve. Each thread reserves "the last seat" for its own buyer. Both buyers get a confirmation.

Step 4: Both threads update. Thread A lowers the count to 0. Thread B lowers it again, to -1.

The diagram below shows the same four steps over time. The middle row shows the value of seats_left at each moment.

Without a mutex, both threads read 1 seat left before either one lowers the count, so the count ends at -1
Without a mutex, both threads read 1 seat left before either one lowers the count, so the count ends at -1

The website sold one seat to two people, and the count of seats left is now negative. Nothing crashed, and no error appeared in the logs.

This bug is a race condition. The two threads "race" through the same code, and the result depends on which one gets where first. The Race Conditions and Critical Sections lesson explains the idea in detail. This lesson is about the tool that fixes it.

Why Testing Misses It

The bug appears only when two threads are inside the booking code at the same moment. On a developer's laptop with one test user, that never happens. On sale day, with thousands of fans, it happens again and again.

Being careful or testing more cannot fix this bug. The code needs a rule: only one thread at a time may run the check and the update. A mutex is that rule, built into the program.

Before you look at the fix, predict what the broken code does with 20 buyers and 10 seats.

Quiz

Ten seats are left, and 20 buyer threads run the booking code at the same moment with no mutex. Each buyer checks the count, waits 20 ms to reserve a seat, and then lowers the count. How many tickets does the site sell?

Click an option to answer

Part 2: What a Mutex Is

The Definition

A mutex is a lock that only one thread can hold at a time. A thread locks the mutex before it enters the critical section, and it unlocks the mutex when it leaves. While one thread holds the mutex, every other thread that tries to lock it must wait.

A coffee shop with one restroom and one key works the same way. A customer takes the key from the counter, uses the room, and brings the key back. Anyone else who needs the room waits at the counter until the key returns. In a program, the key is the mutex, and the room is the critical section. The customers waiting at the counter are the blocked threads.

A mutex follows four rules:

  1. Only one owner. At any moment, at most one thread holds the mutex. That thread is its owner.

  2. Others wait. A thread that tries to lock a mutex that another thread holds stops and waits. It is blocked. After a very short first try, it uses no CPU time while it waits.

  3. The owner unlocks. In Java, C++, and C#, only the owner may unlock the mutex. Python's basic threading.Lock is an exception, because any thread may release it. Your code should still let only the owner release it.

  4. One thread goes next. When the owner unlocks, one thread gets the mutex and continues. Usually it is one of the waiting threads. The others keep waiting for their turn.

What a Mutex Is Not

A mutex does not protect data by itself. It only stops threads that also lock it. Suppose one function locks the mutex before it changes seats_left. Another function changes seats_left without locking. The second function can still break the count. The mutex works only when every piece of code that touches the shared data uses it.

A mutex is not a queue either. When several threads wait, most mutexes make no promise about which one goes next. The thread that waited longest does not always win.

A mutex is also not the same as a semaphore. A semaphore can let several threads in at once, such as 4 threads for 4 database connections. A semaphore also has no owner, so any thread may release it. The Semaphore lesson covers it.

Part 3: Fixing the Ticket Sale

The Code

The program below runs the ticket sale twice, with 10 seats, 20 buyers, and 20 ms to reserve a seat. The first version has no mutex. The second version locks one mutex around the check and the update. Each buyer is one thread, and the program prints the tickets sold, the seats left, and the time.

Python3
Python3

. . . .

Here are two real runs of the Python version on one test machine:

10 seats, 20 buyers, 20 ms to reserve a seat Without a mutex: tickets sold 20, seats left -10, 22 ms With a mutex : tickets sold 10, seats left 0, 204 ms 10 seats, 20 buyers, 20 ms to reserve a seat Without a mutex: tickets sold 20, seats left -10, 22 ms With a mutex : tickets sold 10, seats left 0, 204 ms

Without a mutex, the site sold 20 tickets for 10 seats. All 20 buyers checked the count before any of them lowered it, so all 20 saw a free seat. With a mutex, the site sold exactly 10 tickets, and the last 10 buyers correctly found no seat left.

The other languages gave the same kind of result. C++ and C# also sold 20 tickets without the mutex. Java printed 19 tickets sold in one run and 18 in another. Java did not really sell fewer seats. All 20 buyers passed the check, but some updates to the counters were lost. Two threads read the same old value, and both wrote back the same new value, so one change disappeared. In the first Java run, the two counters do not even agree: 19 tickets sold, but the seat count fell only to -8. That is a second race, in addition to the first one. With the mutex, every run in every language sold exactly 10.

Notice how little changed in the code. The booking steps are the same in both versions. The fix only wraps them in a lock and an unlock.

Notice also what the C++ version does differently. In C++, two threads that change a plain int without a lock cause undefined behavior. That means the language makes no promise about what happens. So the broken C++ version uses atomic counters. Each single read or write is then safe, yet the program still oversells. Safe single steps do not make the whole check-and-update safe.

What the Mutex Changes, Step by Step

Go back to the last seat and the two buyers. This time, both threads lock the same mutex first.

Step 1: Thread A locks the mutex. The mutex is free, so Thread A becomes its owner and enters the critical section.

Step 2: Thread B tries to lock it. Thread A still holds the mutex, so Thread B stops and waits. It does not read seats_left yet.

Step 3: Thread A finishes. Thread A sees 1 seat, reserves it, lowers the count to 0, and unlocks the mutex.

Step 4: Thread B continues. Thread B now gets the mutex. It reads seats_left, sees 0, and tells its buyer that the concert is sold out.

The diagram below shows the same handoff over time.

Thread B waits while Thread A holds the mutex, then takes the mutex when Thread A unlocks it
Thread B waits while Thread A holds the mutex, then takes the mutex when Thread A unlocks it

The Cost of Being Correct

The fixed version was about 10 times slower in Python: 204 ms instead of 22 ms. The reason is simple. The 10 sales now happen one after another, and each one takes 20 ms, so 10 sales take about 200 ms. In Java, C++, and C#, the fixed version took about 310 ms. On that test machine, the operating system rounded each 20 ms sleep in those languages up to about 31 ms.

The fast version was fast because it was wrong. A correct ticket sale must handle the last seats one buyer at a time. The goal is to keep that one-at-a-time part as small as possible, which Part 5 explains.

Part 4: Always Unlock the Mutex

Suppose a thread locks the mutex and then the reservation fails with an error. If the error skips the unlock line, the mutex stays locked forever. Every other buyer waits for a mutex that no thread will ever release, and the ticket site stops responding.

The code below shows the mistake in Java and the safe version next to it:

// Unsafe: if reserveSeat() throws, unlock() never runs lock.lock(); reserveSeat(); lock.unlock(); // Safe: finally runs on every path, including an exception lock.lock(); try { reserveSeat(); } finally { lock.unlock(); }

Every language has a way to unlock automatically, and you should always use it:

<span style="white-space:nowrap">Language</span><span style="white-space:nowrap">Safe</span> <span style="white-space:nowrap">way</span> to <span style="white-space:nowrap">lock</span>When it unlocks
Python<span style="white-space:nowrap">with lock:</span>When the with block ends, even after an exception
Java<span style="white-space:nowrap">lock.lock()</span> <span style="white-space:nowrap">then</span> <span style="white-space:nowrap">try</span> <span style="white-space:nowrap">and</span> <span style="white-space:nowrap">finally { lock.unlock(); }</span>, or a <span style="white-space:nowrap">synchronized</span> <span style="white-space:nowrap">block</span>When finally runs, or when the synchronized block ends
C++std::lock_guard<std::mutex> guard(lock);When guard goes out of scope, even after an exception
C#<span style="white-space:nowrap">lock (seatLock) { ... }</span>When the block ends, even after an exception

Notice that none of these leaves the unlock to the programmer's memory. The language runs it for you on every path out of the critical section.

Part 5: What Goes Inside the Lock

The critical section is the code between lock and unlock. Choosing what goes there is the most important decision when you use a mutex. If too little goes inside, the race comes back. If too much goes inside, the threads wait for no reason.

What belongs inside:

  • The check and the update together. The check seats_left > 0 and the change seats_left -= 1 must happen inside one lock. If the lock covered them separately, two threads could still both pass the check.
  • Every change to the shared data. Both seats_left and tickets_sold change inside the same lock, so no thread can see one updated and the other not.
  • Every read of the shared data. A page that shows "3 seats left" must lock too. Without the lock, it may read an old value. It may also see one field already changed and the other not yet changed. In C++, an unlocked read of a plain variable that another thread changes is also undefined behavior.

What stays outside:

  • Work that uses no shared data, such as building the PDF ticket for one buyer.
  • Slow work, such as sending the confirmation email or writing a log line.
  • Calls to other systems, such as a network request, unless the shared data truly depends on their result.

The numbers show why this matters. Suppose sending the confirmation email takes 300 ms. If the email is sent inside the lock, 10 sales take at least 3 seconds. Each buyer waits for every email before theirs. If the email is sent after the unlock, the next buyer goes ahead while the email is still sending.

Part 6: Common Mistakes

Mistake 1: Locking Only the Writes

A thread that only reads shared data still needs the lock. A reader without the lock can see a half-finished change, such as a new tickets_sold with an old seats_left. Lock every read and every write of the same data with the same mutex.

Mistake 2: Each Thread Uses Its Own Mutex

A mutex works only when all threads lock the same mutex object. The code below creates a new mutex on every call, so every thread gets its own lock and nobody ever waits:

def buy(): lock = threading.Lock() # wrong: a new lock for every call with lock: if seats_left > 0: ...

The fix is to create one mutex next to the data it protects, as the Concert class does in the code above.

Mistake 3: Locking the Same Mutex Twice

Some mutexes let their owner lock them again, and some do not. A mutex that lets its owner lock it again is called reentrant.

<span style="white-space:nowrap">Language</span>Basic mutexCan the owner lock it again?
Python<span style="white-space:nowrap">threading.Lock</span>No. The thread waits for itself forever. Use threading.RLock if you need this.
JavaReentrantLock, synchronizedYes
C++std::mutexNo. Locking it twice from one thread is undefined behavior. Use std::recursive_mutex if you need this.
C#lock statementYes

This mistake usually appears when one locked method calls another method that locks the same mutex.

Mistake 4: Holding the Lock During Slow Work

Part 5 showed the cost: a 300 ms email inside the lock makes every other buyer wait 300 ms more. Do the slow work after the unlock.

Mistake 5: Two Mutexes in Opposite Order

Some code needs two mutexes, such as one for seats and one for payments. Thread A locks seats and then payments. At the same time, Thread B locks payments and then seats. Each thread can end up holding one mutex and waiting for the other. Neither can ever continue. This is a deadlock.

The usual fix is to pick one order and always lock the mutexes in that order. The Deadlock, Starvation, and Livelock lesson explains this fix and two others.

Part 7: How a Mutex Works Inside

You can use a mutex well without knowing its inner workings. A short look still helps you understand its cost.

A mutex is a small piece of memory. It holds a flag that says "locked" or "free," and the operating system keeps a list of the threads that wait for it.

Locking a free mutex. The thread uses an atomic CPU instruction that changes the flag from "free" to "locked" in one step. Two threads cannot both succeed, because the hardware finishes one instruction before the other starts. This path is very fast, roughly a few tens of nanoseconds on a typical modern machine.

Locking a held mutex. The thread may try again a few times in a quick loop. If the mutex is still held, it asks the operating system to put it to sleep. The thread is then blocked, as the Thread Life Cycle and Scheduling lesson describes.

Unlocking. The owner sets the flag back to "free." If threads are waiting, the operating system wakes one of them.

Putting a thread to sleep and waking it up again costs a few microseconds. That is about a hundred times more than the fast path. So a mutex is cheap when threads rarely compete for it and costly when many threads want it at once. When many threads want the same lock, people call that lock contention. Keeping the critical section short is the best way to reduce it.

Part 8: Mutex or Another Tool?

A mutex is the general tool for "one thread at a time." Some problems have a better fit. The table below lists the common cases and where this course covers each one.

What you needBetter toolWhere to learn it
Add 1 to one counter, safelyAn atomic counterProtecting a Critical Section with a Lock
Many threads read, and one thread sometimes writesA read/write lockRead/Write Locks
Let at most N threads in at onceA semaphoreSemaphore
Wait until another thread changes somethingA condition variableCondition Variables
Change several pieces of shared data togetherA mutexThis lesson

The ticket sale needs the last row. The check and the two counters must change together, and a mutex is the simplest way to keep them together.

FAQs

Q: Is a mutex the same as a lock?

Mostly, yes. "Lock" is the general word, and a mutex is the most common kind of lock. Java calls it a ReentrantLock or uses synchronized, Python calls it threading.Lock, C++ calls it std::mutex, and C# uses the lock statement. C# also has a class named Mutex. It is a slower kind that can work across separate programs, so inside one program, use the lock statement.

Q: Does a mutex make my program slow?

Only the critical section runs one thread at a time. Everything outside it still runs in parallel. A program with a short critical section loses very little speed. A program that holds the lock during slow work can lose a lot.

Q: Which waiting thread gets the mutex next?

Usually there is no promise. Most mutexes do not track which thread came first. This is faster, but it is not fair, and one thread can wait much longer than the others. Java offers a fair mode, new ReentrantLock(true), which lets threads in roughly in the order they asked, at some cost in speed.

Q: Python has a Global Interpreter Lock. Do I still need a mutex in Python?

Yes. In the standard Python build, the Global Interpreter Lock lets only one thread run Python code at a time. But Python can switch threads between any two steps, and it always switches when a thread waits. The ticket demo proves it. Each buyer let other threads run during its 20 ms reservation. Without a mutex, the Python version sold 20 tickets for 10 seats.

Q: If only one thread changes the data, do other threads need the lock to read it?

Yes, in most cases. A reader without the lock can see a half-finished change. In Java and C#, it may not even see the latest value. The simplest safe rule is that every read and every write of shared data uses the same lock.

Key Takeaways

  • A mutex lets only one thread at a time run the critical section. A thread locks it before the shared work and unlocks it after. Other threads wait.
  • A race condition can sell one seat twice without any error. In the demo, the broken version sold 20 tickets for 10 seats, and the mutex version sold exactly 10 in every run.
  • The check and the update must sit inside the same lock. Making each step safe on its own is not enough, as the C++ atomic version showed.
  • Always unlock with a tool that runs on every path: with in Python, finally or synchronized in Java, std::lock_guard in C++, and the lock statement in C#.
  • Keep the critical section small. Put every read and write of the shared data inside, and keep slow work, such as sending email, outside.
  • Watch for the common mistakes. They are unlocked reads, a new mutex per call, locking twice, slow work inside the lock, and two mutexes in opposite orders.
  • In a coding interview, name the shared data and the lines that form the critical section. Protect them with one mutex, unlocked in finally or by with. Then say what you kept outside the lock, and why.

A mutex lets one thread in at a time, even when every thread only wants to read. The next lesson, Read/Write Locks, shows a lock that lets many readers in together.

Check Your Understanding

1. Two threads run if seats_left > 0: seats_left -= 1 on the last seat, with no mutex. What can happen?

<details> <summary>Show answer</summary>

Both threads can sell the seat. Both can read 1 before either one lowers it. Then both lower the count, and it ends at -1.

</details>

2. A developer locks the mutex around seats_left -= 1 but not around the check seats_left > 0. Is the code safe?

<details> <summary>Show answer</summary>

No. Two threads can still both pass the check before either one takes the lock. The check and the update must be inside the same lock.

</details>

3. A Java method calls lock.lock(), then reserveSeat(), then lock.unlock(), with no try block. What goes wrong if reserveSeat() throws?

<details> <summary>Show answer</summary>

The mutex is never unlocked. Every other thread that tries to lock it waits forever. Putting unlock() in a finally block fixes it.

</details>

4. Sending the confirmation email takes 300 ms. Should it be inside or outside the critical section?

<details> <summary>Show answer</summary>

Outside. The email does not change shared data. Inside the lock, it would make every other buyer wait an extra 300 ms.

</details>
Flashcards Review

What is a mutex?

1 / 12
Shouvik Pradhan

Shouvik Pradhan

· 2 years ago

The primary use of the join() method is to pause the current thread (the thread that calls join()) until another thread (the thread specified as the argument to join()) terminates

Reading Progress

0%


Vote for new content

On This Page

Know the Vocabulary

Part 1: The Last Seat Problem

How One Seat Gets Sold Twice

Why Testing Misses It

Part 2: What a Mutex Is

The Definition

What a Mutex Is Not

Part 3: Fixing the Ticket Sale

The Code

What the Mutex Changes, Step by Step

The Cost of Being Correct

Part 4: Always Unlock the Mutex

Part 5: What Goes Inside the Lock

Part 6: Common Mistakes

Mistake 1: Locking Only the Writes

Mistake 2: Each Thread Uses Its Own Mutex

Mistake 3: Locking the Same Mutex Twice

Mistake 4: Holding the Lock During Slow Work

Mistake 5: Two Mutexes in Opposite Order

Part 7: How a Mutex Works Inside

Part 8: Mutex or Another Tool?

FAQs

Key Takeaways

Check Your Understanding