Aller au contenu

Langue de l’interface : FR. Contenu éditorial : anglais. Les prix concernent Royaume-Uni.

Sir CompareComparatifs avec des preuves
Royaume-Uni · GBP

Actualité

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

Mis à jour

Photo d’illustration: AI Tools & SaaS: Code on computer monitor (Unsplash)
Photo d’illustration

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

Du matériel pour essayer l’IA chez soi

Liens affiliés : nous pouvons percevoir une commission sur les achats éligibles, sans effet sur nos données ni nos classements. Ils ouvrent les résultats de recherche d’Amazon : prix et disponibilité s’y affichent.

Vidéo

Ce qui a changé

  • Page mise à jour

Comment je classe les produits

La lettre de Sir Compare

Du nouveau sur Outils IA et SaaS ? Je vous écris.

Choisissez vos sujets : je n’écris que lorsqu’il y a du neuf — un guide, une actualité, un prix vérifié qui baisse.

Étape 1 sur 2

Qu’est-ce qui vous intéresse ?

Choisissez-en autant que vous voulez. Sans choix, vous recevez les nouveautés de toutes les rubriques.

Ce que vous voulez recevoir
  • Seulement vos choix
  • Jamais d’e-mail vide
  • Un clic pour partir

Votre assistant

Ouvrir la page complète →