‹ nazad u kafanu · back to the bar
Tavern Tales · priča

Race Condition

· 2 min read · sve priče

It's late. The neon hums. There is exactly one glass of rakija left on the bar, and — because the universe has a sense of humour — two thirsty patrons spot it at the same instant.

What happens next is the oldest bug in computer science, acted out in a tavern.

Dva gosta, jedna čaša

Both reach. Both check first, like polite people do:

if (bar.rakija.available) {   // gost A: true.  gost B: also true.
  bar.rakija.pour()           // both pour.
}

Two hands, one glass. It tips. Rakija everywhere. Nobody drinks.

„Ko prvi devojci, njemu i devojka." · first come, first served — except nobody agreed on what first means when both arrived in the same nanosecond.

This is a race condition: the outcome depends on who got there first, and the answer is yes.

Pingvin reaches for the towel

The bartender doesn't add glasses. He adds a rule. Behind the bar there is one towel, and you may only pour while holding the towel:

bar.towel.acquire()
try {
  if (bar.rakija.available) bar.rakija.pour()
} finally {
  bar.towel.release()        // always give the towel back. always.
}

One towel, one pour at a time. The race is gone. The mutex works. Živeli —

…osim kad se zaglave

— except the next night, two regulars each want *rakija and meze*. There's one towel for the bottle and one for the kitchen. Gost A grabs the bottle-towel and waits for the kitchen-towel. Gost B grabs the kitchen-towel and waits for the bottle-towel.

Neither lets go. Neither moves. The bar freezes at 1 a.m. forever. Deadlock.

The fix is a house rule so simple it's almost rude:

  • Always reach for the bottle-towel first, then the kitchen-towel.
  • Never the other way around.

Acquire your locks in the same order everywhere, and the circle can never close.

Šta zaista radi

Here's the thing, though. The best kafana doesn't run on locks. Locks are what you reach for when the resource is scarce — one glass, one towel, one chance.

Pingvin's actual secret is older than threads: the house always has more rakija. The cellar (/podrum) never runs dry. When the resource is effectively infinite — append-only, immutable, copied-not-shared — there is nothing to race for.

The cheapest concurrency bug to fix is the one you designed out by refusing to share the last glass.

So: lock when you must, order your locks when you must lock more than one — but whenever you can, just pour everyone their own.

Nazdravlje. The next one's on the house. 🍻