Vai al contenuto

Lingua interfaccia: IT. Contenuti editoriali: inglese. Prezzi riferiti a Regno Unito.

Sir CompareConfronti con le proveChiedi a Sir CompareChiediTelegram
Regno Unito · GBP

Notizia

Mutex explained: atomic swap, spin-wait cost, deadlock risk

Aggiornato

Foto illustrativa: AI Tools & SaaS: Code on computer monitor (Unsplash)
Foto illustrativa

The problem: two withdrawals, one balance

Two processes can both check a balance, both see enough money, and both subtract. The result is a wrong balance and money dispensed twice. The fix is to protect the check-and-subtract block so only one thread runs it at a time.

A lock before the block and an unlock after it does that job. The analogy is a bathroom door: if it's locked, you wait; when the person leaves, the resource is free. The lock only works if everyone respects it, and the unlock must always happen.

That leaves the real question: how do you build a lock that doesn't have the same race inside it?

One hardware instruction does the trick

A naive lock — check if free, then set it — repeats the original bug. Two threads can both read "not locked" and both think they hold it.

So the hardware provides something extra: an atomic read-and-swap. The CPU reads the old value from a memory slot and writes a new one, with nothing able to slip in between. Either you see the value after the swap, or you were beaten to it.

With that, a lock variable is enough. The swap is indivisible, so only one caller can win. Unlocking is just writing zero back to the mutex.

Spinning is fast but expensive

If the lock is taken, the simple version keeps retrying in a tight loop. CPUs run billions of instructions a second, so this is like rattling the bathroom door nonstop. It works, but it pegs the CPU at 100% doing nothing useful.

For latency-sensitive work, that busy-wait can be an acceptable trade. In a general system, the operating system steps in: after a few failed attempts it puts the process to sleep and runs something else. Unlocking then also has to wake the waiters.

Reordering can break a correct-looking lock

Compilers and CPUs may move instructions around when they think the order doesn't matter. Speculative execution makes this worse: an update to the balance could run earlier than expected.

The exchange instruction usually carries a barrier. It tells the CPU not to hoist loads above it, and tells the compiler not to shuffle code across it. Unlocking needs similar care.

x86 chips tend to keep order anyway. High-performance ARM processors reorder far more aggressively, so the barrier matters there. A lock that looks right in source can still be wrong on the chip.

Two locks, one deadlock

A lock per account beats one lock for the whole bank. But a transfer needs both accounts locked, and that opens a trap.

You lock A, then wait for B. Meanwhile someone transferring the other way locks B and waits for A. Neither can finish. That is a deadlock, the same shape as the dining philosophers problem.

Databases may use a timeout and roll back. The usual fix is a rule: always lock accounts in numerical order. Then one side waits and one wins. Discipline in lock order is what keeps you out of trouble.

What this means for your code

The mutex is one primitive, and almost everything else gets built on top of it. Modern hardware offers other atomic operations too, but the swap is the foundation.

If you write threaded code, the practical checks are simple. Always unlock, even on error paths. And fix an order for any set of locks you take together.

I haven't benchmarked any of this myself; the numbers and behaviour here come from the walkthrough. The next thing worth checking is how your platform's memory barriers are documented.

Related coverage

Source: Computerphile · computer science and AI (UK)'s video

Hardware per provare l'AI in locale

Link affiliati: possiamo ricevere una commissione sugli acquisti idonei, e non cambia i nostri dati né le classifiche. Aprono i risultati di ricerca di Amazon: prezzi e disponibilità si vedono lì.

Video

Cosa è cambiato

  • Pagina aggiornata

Come metto in fila i prodotti

La posta di Sir Compare

Novità su Strumenti AI e SaaS? Te le scrivo io.

Scegli cosa ti interessa: ti scrivo solo quando esce qualcosa di nuovo — una guida, una notizia, un prezzo verificato che scende.

Passo 1 di 2

Cosa ti interessa?

Scegline quante vuoi. Se non scegli niente, ricevi le novità di tutte le sezioni.

Cosa vuoi ricevere
  • Solo quello che scegli
  • Mai email vuote
  • Esci con un clic

Il tuo assistente

Apri la pagina completa →