AlgoViz
Operating Systems
Operating Systems · MediumLesson 7 of 12

Locks & mutexes

A race condition happens when two threads change the same thing at once and the answer comes out wrong. The fix is simple to say: make sure only ONE thread can touch the shared thing at a time. The tool that does this is a lock — and because it gives exactly one thread exclusive use, it's often called a mutex, short for 'MUTual EXclusion'. With a lock in place, the lost update simply can't happen.

The key to a single bathroom

Picture one bathroom at a party with a single key hanging by the door. The rule: you can only go in if you're holding the key. Whoever grabs the key goes in and locks the door; everyone else has to WAIT outside. When that person comes out, they hang the key back, and the next person can take it and go in. That's exactly what a lock does for shared data. The 'bathroom' is the shared counter. The 'key' is the lock. A thread must grab the lock before it touches the counter, and only one thread can hold the lock at a time. Everyone else waits. No two threads are ever inside at once — so they can never collide.

The critical section: the part you protect

🧮Counter = 5🔒 Lockone key onlyCritical sectionThread AHAS the key — workingholds keyThread BWAITS for the keyblocked
Thread A holds the lock and runs its full read-add-write inside the critical section. Thread B is blocked outside until the key comes back.

You don't lock the WHOLE program — that would make threads useless, since they'd never run at the same time. You only lock the short, dangerous stretch where they touch the shared thing. That protected stretch of code has a name: the critical section. For our counter, the critical section is the three little steps that were causing trouble: read the value, add one, write it back. The deal is: grab the lock, do all three steps, release the lock. Because a thread holds the key for the whole read-add-write, no other thread can sneak into the gap in the middle. That gap was the entire cause of the race — and the lock seals it shut.

Watch the lost update get prevented

Remember the broken version: both threads read 5, both wrote 6, and a +1 vanished. Now run it again with a lock, starting at 5: • Thread A grabs the lock and goes in. It reads 5, adds 1, writes 6 — its full turn, uninterrupted. Then it releases the lock. • Thread B has been WAITING outside this whole time. Now the key is free, so B grabs it and goes in. It reads… 6 (the value A just wrote!), adds 1, writes 7. Then it releases. Final answer: 7 — exactly right. The difference is that B no longer reads the stale 5, because it wasn't allowed in until A had completely finished. One thread at a time, each seeing the other's finished work. That's mutual exclusion doing its job.

The catch: waiting, and deadlock

Locks aren't free. While one thread holds the lock, every other thread that wants it has to STOP and wait. So a lock that's held too long, or that protects too much, can make your threads stand around in line instead of working — that's the cost of safety, and it can slow a program down. There's a sharper danger too. If Thread A holds lock 1 and waits for lock 2, while Thread B holds lock 2 and waits for lock 1, neither can ever move — each is waiting for a key the other refuses to let go of. They're frozen forever. That's called a deadlock, and it's a whole topic of its own coming next. The takeaway for now: locks make sharing safe, but you have to use them carefully — grab them for as short a time as possible, and be careful when holding more than one.

It's a tradeoff

Option👍 Pro👎 Con
No lock at allFastest — threads never wait for each other.Unsafe whenever they share data: race conditions and lost updates.
One big (coarse) lockSimple and safe — easy to reason about, hard to get wrong.Threads spend lots of time waiting in line, even for unrelated work — so it can be slow.
Many small (fine-grained) locksThreads only wait when they truly touch the SAME thing, so more runs in parallel.Trickier to get right — more locks means more chances of deadlock and bugs.

Questions you might have

What does 'mutex' actually mean?

It's just short for 'mutual exclusion' — a fancy way of saying 'only one at a time'. A mutex is a lock whose whole job is to make sure two threads are mutually excluded from the shared thing: when one is in, the other is shut out. People say 'lock' and 'mutex' to mean basically the same thing.

What happens to the thread that doesn't get the lock?

It waits. It pauses right at the point where it tried to grab the lock and just stands in line, doing nothing, until the lock is free. The OS quietly sets it aside so it isn't burning the CPU while it waits, then wakes it up the moment its turn comes.

If locks make threads wait, don't they cancel out the point of threads?

Only if you lock too much. The trick is to lock ONLY the tiny critical section — the few lines that touch shared data — and leave everything else unlocked. Then threads run side by side most of the time and only line up for the brief moment they touch the same thing. A good lock protects a little; a bad one protects everything.

What if a thread grabs the lock and never gives it back?

Then everyone else waits forever — the lock is stuck held. That's why you must always release a lock when you're done (and even if something goes wrong partway). If two threads each hold a lock the other needs, they can both wait forever on purpose — that's called deadlock, and it's the next topic.

Does the second thread read the new value or the old one?

The NEW one — that's the whole win. Because the second thread wasn't allowed in until the first fully finished its read-add-write, by the time it reads, the counter already holds the first thread's updated value. So instead of both reading 5, the second one reads 6 and correctly makes it 7.

🧠A lock (mutex = 'mutual exclusion') lets only ONE thread into the critical section at a time, like the key to a single bathroom — everyone else waits. That seals the gap that caused the race, so the lost update can't happen. The cost: waiting threads, and the risk of deadlock if you hold locks carelessly.
✅ Check yourself4 quick questions — prove the idea stuck.Start →🧭 Take it furtherA new system you haven't read about — would you reach for this idea, and what does it cost?Try it →

Best read after: Race conditions