« cannot be shared between threads safely » : Send, Sync et Arc<Mutex<T>> en Rust (E0277) "cannot be shared between threads safely": Send, Sync and Arc<Mutex<T>> in Rust (E0277)

Send dit qu'une valeur peut changer de thread, Sync que plusieurs threads peuvent la partager : rustc vérifie les deux à chaque thread::spawn. Pourquoi Arc<Cell<T>> est refusé (E0277), pourquoi Arc seul ne permet pas de modifier (E0596), ce que fait le garde d'un Mutex, et ce que le compilateur ne voit pas : le verrou empoisonné et l'interblocage. Animation et sorties réelles de rustc.Send says a value can change threads, Sync that several threads can share it: rustc checks both on every thread::spawn. Why Arc<Cell<T>> is refused (E0277), why Arc alone does not allow mutation (E0596), what a Mutex guard does, and what the compiler does not see: the poisoned lock and the deadlock. Animation and real rustc output.

AuteurAuthor
Ludovic Cleuet
ThèmeTopic
ConcurrenceConcurrency
PubliéPublished

En bref. Déplacer une donnée dans un thread ne suffit pas toujours : encore faut-il que son type supporte le voyage, et le partage. Rust l’exprime avec deux traits marqueurs, Send et Sync, que le compilateur vérifie à chaque thread::spawn. Quand l’un manque, c’est E0277 : cannot be sent between threads safely, ou cannot be shared between threads safely. Et pour modifier une donnée depuis plusieurs threads, il faut deux pièces qui ne font pas le même travail : Arc et Mutex.

Le modèle en une phrase

Send : la valeur peut changer de thread. Sync : plusieurs threads peuvent la lire en même temps. Arc partage la possession, Mutex rétablit l’exclusivité, un thread à la fois : aucun des deux ne suffit seul.

C’est la suite directe de l’article sur les threads et move, qui s’arrêtait sur cette phrase : « spawn exige aussi Send ».

In short. Moving data into a thread isn’t always enough: its type must also support the trip, and the sharing. Rust expresses this with two marker traits, Send and Sync, which the compiler checks on every thread::spawn. When one is missing, it’s E0277: cannot be sent between threads safely, or cannot be shared between threads safely. And to mutate data from several threads, you need two pieces that don’t do the same job: Arc and Mutex.

The model in one sentence

Send: the value can change threads. Sync: several threads can read it at the same time. Arc shares ownership, Mutex restores exclusivity, one thread at a time: neither is enough alone.

It’s the direct sequel to the article on threads and move, which stopped on this sentence: “spawn also requires Send”.

let nom = Rc::new(String::from("Ada"));
thread::spawn(move || println!("{nom}"));
Send et SyncSend and Syncce que rustc vérifie à chaque spawnwhat rustc checks on every spawnRc<String>envoyersendnon : compteur non atomiqueno: non-atomic counterpartagersharenonnomodifiermutatenonnoSendSyncVec<i32>Rc<String>nonnononnoArc<Vec<i32>>Cell<i32>nonnoArc<Cell<i32>>nonnononnoMutex<i32>Arc<Mutex<i32>>chaque case : une compilation, rustc 1.100each cell: one compilation, rustc 1.100Send : la valeur peut-elle partir dans un autre thread ?Send: can the value leave for another thread?E0277 : `Rc<String>` cannot be sent between threads safelyE0277: `Rc<String>` cannot be sent between threads safely
  1. spawn exige une closure Send : tout ce qu'elle emporte doit pouvoir changer de thread. Un Rc ne le peut pas : son compteur n'est pas atomique, et deux threads qui clonent en même temps le fausseraient. rustc refuse (E0277).spawn requires a Send closure: everything it takes along must be able to change threads. An Rc can't: its counter isn't atomic, and two threads cloning at the same time would corrupt it. rustc refuses (E0277).
  2. Arc compte avec des opérations atomiques : il est Send et Sync, chaque thread reçoit son clone. Mais plusieurs propriétaires veut dire lecture seule : push est refusé (E0596). Arc partage, il ne permet pas de modifier.Arc counts with atomic operations: it is Send and Sync, each thread gets its own clone. But several owners means read-only: push is refused (E0596). Arc shares, it does not allow mutation.
  3. Ajouter une Cell pour modifier ? Cell modifie à travers un & sans aucune protection : deux threads écriraient en même temps. Elle n'est pas Sync, et un Arc<T> n'est Send que si T est Sync. E0277, côté partage cette fois.Add a Cell to mutate? Cell mutates through a & with no protection at all: two threads would write at the same time. It isn't Sync, and an Arc<T> is only Send if T is Sync. E0277, on the sharing side this time.
  4. Mutex apporte ce qui manquait : la modification à travers un &, mais un seul thread à la fois. Il est Sync, donc Arc<Mutex<T>> est Send. Arc partage la possession, Mutex rétablit l'exclusivité : total 4000, aucune écriture perdue.Mutex brings what was missing: mutation through a &, but one thread at a time. It is Sync, so Arc<Mutex<T>> is Send. Arc shares ownership, Mutex restores exclusivity: total 4000, no lost write.
Send et Sync en Rust : Send dit qu’une valeur peut changer de thread, Sync que plusieurs threads peuvent la partager. Rc n’est ni l’un ni l’autre, Cell n’est pas Sync, et Arc<Mutex<T>> réunit le partage (Arc) et l’exclusivité (Mutex).Send and Sync in Rust: Send says a value can change threads, Sync that several threads can share it. Rc is neither, Cell is not Sync, and Arc<Mutex<T>> combines sharing (Arc) and exclusivity (Mutex).

L’erreur : un compteur partagé avec Cell

On veut un compteur que plusieurs threads incrémentent. Arc pour le partager, Cell pour le modifier à travers une référence partagée : sur le papier, tout y est.

use std::cell::Cell;
use std::sync::Arc;
use std::thread;

fn main() {
    let total = Arc::new(Cell::new(0));
    let copie = Arc::clone(&total);
    let h = thread::spawn(move || {
        copie.set(copie.get() + 1);
    });
    h.join().unwrap();
}
error[E0277]: `Cell<i32>` cannot be shared between threads safely
   --> arc_cell.rs:8:27
    |
  8 |       let h = thread::spawn(move || {
    |  _____________-------------_^
    | |             |
    | |             required by a bound introduced by this call
  9 | |         copie.set(copie.get() + 1);
 10 | |     });
    | |_____^ `Cell<i32>` cannot be shared between threads safely
    |
    = help: the trait `Sync` is not implemented for `Cell<i32>`
    = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI32` instead
    = note: required for `Arc<Cell<i32>>` to implement `Send`

Trois lignes à lire dans l’ordre inverse. spawn exige une closure Send. La closure contient un Arc<Cell<i32>>, qui devrait donc être Send. Et il ne l’est pas, parce que Cell<i32> n’est pas Sync.

Le danger est concret. copie.set(copie.get() + 1) fait trois choses : lire, ajouter, écrire. Deux threads qui le font en même temps peuvent lire tous les deux 0 et écrire tous les deux 1. Un ajout est perdu, sans erreur ni panic. C’est une course aux données, et rustc la refuse avant qu’elle existe.

Send et Sync : deux questions différentes

 Send : la valeur change de thread        Sync : la valeur reste, on la partage

 thread A        thread B                 thread A        thread B
 ┌───────┐       ┌───────┐                ┌───────┐
 │ T     │ ────▶ │ T     │                │ T     │ ◀──── &T
 └───────┘       └───────┘                └───────┘
  n'y a plus      seul                       ▲
  accès           propriétaire               └──── &T (A lit aussi)
  • Send : on peut déplacer la valeur dans un autre thread. Presque tout est Send. L’exception connue est Rc, dont le compteur n’est pas atomique.
  • Sync : plusieurs threads peuvent y accéder en même temps à travers un &. La définition exacte tient en une ligne : T est Sync si &T est Send.

Ce sont des traits marqueurs : aucune méthode, rien à écrire. Le compilateur les déduit de la composition du type. Une struct dont tous les champs sont Send est Send.

Chaque case de ce tableau a été vérifiée en compilant fn exige<T: Send>() {} (ou Sync) avec rustc 1.100 :

TypeSendSyncPourquoi
i32, String, Vec<i32>ouiouiaucune mutation à travers un &
Rc<i32>nonnoncompteur non atomique
Arc<i32>, Arc<Vec<i32>>ouiouicompteur atomique, contenu en lecture seule
Cell<i32>, RefCell<i32>ouinonmutation à travers un &, sans protection
Arc<Cell<i32>>nonnonArc<T> exige T: Sync
Mutex<i32>, AtomicU32ouiouimutation à travers un &, synchronisée
Arc<Mutex<i32>>ouiouiles deux réunis
MutexGuard<i32>nonouidoit être rendu par le thread qui a pris le verrou
*const i32nonnonpointeur brut : aucune garantie

La ligne Cell explique l’erreur du début. Une Cell est Send : la déplacer dans un thread est permis, et ce programme affiche join : Ok(1) :

let c = Cell::new(0);
let h = thread::spawn(move || {
    c.set(c.get() + 1);
    c.get()
});
println!("join : {:?}", h.join());

Un seul thread y accède à la fois, donc rien ne peut mal tourner. Ce qui est interdit, c’est le partage. Et un Arc est précisément un outil de partage : chaque clone donne accès à la même valeur. Voilà pourquoi Arc<T> n’est Send que si T est Sync.

Arc seul : partagé, donc en lecture seule

Retirons la Cell. Un Arc<Vec<i32>> passe d’un thread à l’autre sans difficulté. Mais essayons d’y écrire :

let v = Arc::new(vec![1, 2, 3]);
let copie = Arc::clone(&v);
let h = thread::spawn(move || {
    copie.push(4);
});
error[E0596]: cannot borrow data in an `Arc` as mutable
 --> arc_push.rs:8:9
  |
8 |         copie.push(4);
  |         ^^^^^ cannot borrow as mutable
  |
  = help: trait `DerefMut` is required to modify through a dereference, but it is not implemented for `Arc<Vec<i32>>`

Ce n’est plus une question de thread. C’est la règle de l’emprunt : modifier demande un accès exclusif, et un Arc existe pour qu’il y ait plusieurs propriétaires. Il ne peut donc donner que des &.

On est coincé entre deux refus :

 Arc<Vec<i32>>     partage : oui      modifier : non (E0596)
 Arc<Cell<i32>>    modifier : oui     partage  : non (E0277)
 Arc<Mutex<i32>>   partage : oui      modifier : oui, un thread à la fois

Mutex : l’exclusivité, vérifiée à l’exécution

Un Mutex<T> enferme une valeur derrière un verrou. Pour y toucher, il faut appeler lock(), qui attend que le verrou soit libre et rend un garde, le MutexGuard :

let total = Mutex::new(0);
let garde = total.lock().unwrap();
println!("verrou pris  : try_lock = {}", total.try_lock().is_ok());
drop(garde);
println!("verrou rendu : try_lock = {}", total.try_lock().is_ok());
{
    let mut g = total.lock().unwrap();
    *g += 1;
}
println!("total : {:?}", total.lock().unwrap());
verrou pris  : try_lock = false
verrou rendu : try_lock = true
total : 1

Deux choses à retenir. Le garde se comporte comme un &mut T : on écrit *g += 1. Et il n’y a pas de unlock() : le verrou est rendu quand le garde est détruit, à la fin du bloc ou par drop. Impossible d’oublier de le rendre, et impossible de toucher à la valeur sans l’avoir pris, puisque la valeur est dans le Mutex.

C’est le même marché que RefCell : la règle « un seul écrivain » est vérifiée à l’exécution plutôt qu’à la compilation. La différence est dans la réaction. Une RefCell déjà empruntée panique. Un Mutex déjà pris fait attendre.

Avec Arc autour, le compteur du début fonctionne :

let total = Arc::new(Mutex::new(0));
let mut poignees = Vec::new();
for _ in 0..4 {
    let copie = Arc::clone(&total);
    poignees.push(thread::spawn(move || {
        for _ in 0..1000 {
            *copie.lock().unwrap() += 1;
        }
    }));
}
for h in poignees {
    h.join().unwrap();
}
println!("total : {}", total.lock().unwrap());
println!("propriétaires : {}", Arc::strong_count(&total));
total : 4000
propriétaires : 1

Quatre threads, mille ajouts chacun, aucun perdu. Dans le temps, cela ressemble à ceci :

 temps ──────────────────────────────────────────────▶

 thread 1   ── lock() ████ garde ████ drop
 thread 2   ────── lock() ░░ attend ░░ ████ garde ████ drop
                                       ▲
                                       └─ le verrou change de main

Chacun son rôle. Arc répond à « qui possède la donnée » : tout le monde, jusqu’au dernier clone. Mutex répond à « qui a le droit d’y écrire maintenant » : celui qui tient le garde.

Ce que le Mutex ne règle pas

Le verrou empoisonné. Pourquoi lock() rend-il un Result ? Parce qu’un thread peut paniquer en tenant le verrou, et laisser la valeur à moitié modifiée :

let h = thread::spawn(move || {
    let mut g = copie.lock().unwrap();
    *g += 1;
    panic!("le thread s'arrête avec le verrou en main");
});
println!("join : erreur ? {}", h.join().is_err());
match total.lock() {
    Ok(g) => println!("valeur : {}", *g),
    Err(e) => println!("verrou empoisonné, valeur : {}", *e.into_inner()),
}
thread '<unnamed>' (537390) panicked at poison.rs:10:9:
le thread s'arrête avec le verrou en main
join : erreur ? true
verrou empoisonné, valeur : 1

Le verrou est bien rendu (le garde est détruit pendant le panic), mais le Mutex est marqué. Le .unwrap() habituel propage alors le panic aux autres threads. Quand la valeur reste cohérente, into_inner() la récupère.

L’interblocage. Deux verrous, deux threads, pris dans l’ordre inverse :

thread::spawn(move || {
    let _ga = a1.lock().unwrap();
    thread::sleep(Duration::from_millis(50));
    let _gb = b1.lock().unwrap();
    tx1.send("thread 1").unwrap();
});

thread::spawn(move || {
    let _gb = b.lock().unwrap();
    thread::sleep(Duration::from_millis(50));
    let _ga = a.lock().unwrap();
    tx.send("thread 2").unwrap();
});

match rx.recv_timeout(Duration::from_millis(500)) {
    Ok(nom) => println!("{nom} a terminé"),
    Err(_) => println!("aucun thread n'a terminé après 500 ms : interblocage"),
}
aucun thread n'a terminé après 500 ms : interblocage
 thread 1   tient a ████████████████▶   attend b ░░░░░░░░▶
 thread 2   tient b ████████████████▶   attend a ░░░░░░░░▶

            chacun attend le verrou que l'autre ne rendra jamais

Ce programme compile sans erreur ni avertissement. Aucune règle de possession n’est violée : chaque accès est exclusif. Rust empêche la course aux données, pas l’interblocage. Le remède est une convention : prendre les verrous toujours dans le même ordre, et les tenir le moins longtemps possible.

Ce que l’image cache

  • Pour un simple compteur, un type atomique suffit. Arc<AtomicU32> avec fetch_add(1, Ordering::Relaxed) donne le même total : 4000, sans verrou ni garde. Mesuré : AtomicU32 fait 4 octets, Mutex<u32> en fait 16.
  • RwLock distingue lecteurs et écrivain. Plusieurs read() en même temps, ou un seul write(). Vérifié : avec deux lecteurs actifs, try_write() échoue. C’est la règle de l’emprunt, à l’exécution et entre threads.
  • Mutex ne rend pas tout partageable. Arc<Mutex<Rc<i32>>> est refusé (E0277, « Rc<i32> cannot be sent between threads safely ») : Mutex<T> n’est Sync que si T est Send, puisque le verrou donne la valeur tour à tour à chaque thread.
  • Le garde ne change pas de thread. MutexGuard n’est pas Send : le verrou doit être rendu par le thread qui l’a pris. Le déplacer dans un autre thread est refusé à la compilation.
  • thread::scope ne change rien à Sync. Emprunter une &Cell depuis un thread scopé donne la même erreur : une &Cell n’est pas Send, précisément parce que Cell n’est pas Sync.
  • Tenir le garde trop longtemps coûte cher. let g = m.lock().unwrap(); garde le verrou jusqu’à la fin du bloc. *m.lock().unwrap() += 1; le rend à la fin de l’instruction.
  • unsafe impl Send existe. C’est ainsi que Arc et Mutex sont eux-mêmes déclarés dans la bibliothèque standard. L’écrire soi-même, c’est promettre au compilateur ce qu’il ne peut plus vérifier.

Pour aller plus loin

The error: a counter shared with Cell

We want a counter that several threads increment. Arc to share it, Cell to mutate it through a shared reference: on paper, it’s all there.

use std::cell::Cell;
use std::sync::Arc;
use std::thread;

fn main() {
    let total = Arc::new(Cell::new(0));
    let copie = Arc::clone(&total);
    let h = thread::spawn(move || {
        copie.set(copie.get() + 1);
    });
    h.join().unwrap();
}
error[E0277]: `Cell<i32>` cannot be shared between threads safely
   --> arc_cell.rs:8:27
    |
  8 |       let h = thread::spawn(move || {
    |  _____________-------------_^
    | |             |
    | |             required by a bound introduced by this call
  9 | |         copie.set(copie.get() + 1);
 10 | |     });
    | |_____^ `Cell<i32>` cannot be shared between threads safely
    |
    = help: the trait `Sync` is not implemented for `Cell<i32>`
    = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI32` instead
    = note: required for `Arc<Cell<i32>>` to implement `Send`

Three lines to read in reverse order. spawn requires a Send closure. The closure contains an Arc<Cell<i32>>, which should therefore be Send. And it isn’t, because Cell<i32> is not Sync.

The danger is concrete. copie.set(copie.get() + 1) does three things: read, add, write. Two threads doing it at the same time can both read 0 and both write 1. One addition is lost, with no error and no panic. That’s a data race, and rustc refuses it before it exists.

Send and Sync: two different questions

 Send: the value changes threads          Sync: the value stays, it is shared

 thread A        thread B                 thread A        thread B
 ┌───────┐       ┌───────┐                ┌───────┐
 │ T     │ ────▶ │ T     │                │ T     │ ◀──── &T
 └───────┘       └───────┘                └───────┘
  no longer       sole                       ▲
  has access      owner                      └──── &T (A reads too)
  • Send: the value can be moved into another thread. Almost everything is Send. The well-known exception is Rc, whose counter isn’t atomic.
  • Sync: several threads can access it at the same time through a &. The exact definition fits in one line: T is Sync if &T is Send.

They are marker traits: no method, nothing to write. The compiler derives them from what the type is made of. A struct whose fields are all Send is Send.

Every cell of this table was checked by compiling fn exige<T: Send>() {} (or Sync) with rustc 1.100:

TypeSendSyncWhy
i32, String, Vec<i32>yesyesno mutation through a &
Rc<i32>nononon-atomic counter
Arc<i32>, Arc<Vec<i32>>yesyesatomic counter, read-only content
Cell<i32>, RefCell<i32>yesnomutation through a &, unprotected
Arc<Cell<i32>>nonoArc<T> requires T: Sync
Mutex<i32>, AtomicU32yesyesmutation through a &, synchronized
Arc<Mutex<i32>>yesyesboth combined
MutexGuard<i32>noyesmust be released by the thread that took the lock
*const i32nonoraw pointer: no guarantee

The Cell row explains the opening error. A Cell is Send: moving it into a thread is allowed, and this program prints join : Ok(1):

let c = Cell::new(0);
let h = thread::spawn(move || {
    c.set(c.get() + 1);
    c.get()
});
println!("join : {:?}", h.join());

Only one thread accesses it at a time, so nothing can go wrong. What is forbidden is sharing. And an Arc is precisely a sharing tool: every clone gives access to the same value. That’s why Arc<T> is only Send if T is Sync.

Arc alone: shared, hence read-only

Let’s remove the Cell. An Arc<Vec<i32>> goes from one thread to another without trouble. But let’s try to write to it:

let v = Arc::new(vec![1, 2, 3]);
let copie = Arc::clone(&v);
let h = thread::spawn(move || {
    copie.push(4);
});
error[E0596]: cannot borrow data in an `Arc` as mutable
 --> arc_push.rs:8:9
  |
8 |         copie.push(4);
  |         ^^^^^ cannot borrow as mutable
  |
  = help: trait `DerefMut` is required to modify through a dereference, but it is not implemented for `Arc<Vec<i32>>`

This is no longer about threads. It’s the borrowing rule: mutating requires exclusive access, and an Arc exists so that there are several owners. So it can only hand out &.

We’re stuck between two refusals:

 Arc<Vec<i32>>     share: yes      mutate: no (E0596)
 Arc<Cell<i32>>    mutate: yes     share:  no (E0277)
 Arc<Mutex<i32>>   share: yes      mutate: yes, one thread at a time

Mutex: exclusivity, checked at run time

A Mutex<T> locks a value away. To touch it, you must call lock(), which waits for the lock to be free and returns a guard, the MutexGuard:

let total = Mutex::new(0);
let garde = total.lock().unwrap();
println!("verrou pris  : try_lock = {}", total.try_lock().is_ok());
drop(garde);
println!("verrou rendu : try_lock = {}", total.try_lock().is_ok());
{
    let mut g = total.lock().unwrap();
    *g += 1;
}
println!("total : {:?}", total.lock().unwrap());
verrou pris  : try_lock = false
verrou rendu : try_lock = true
total : 1

Two things to remember. The guard behaves like a &mut T: you write *g += 1. And there is no unlock(): the lock is released when the guard is destroyed, at the end of the block or through drop. You can’t forget to release it, and you can’t touch the value without taking it, since the value is inside the Mutex.

It’s the same deal as RefCell: the “single writer” rule is checked at run time instead of compile time. The difference is in the reaction. A RefCell that is already borrowed panics. A Mutex that is already taken makes you wait.

With Arc around it, the opening counter works:

let total = Arc::new(Mutex::new(0));
let mut poignees = Vec::new();
for _ in 0..4 {
    let copie = Arc::clone(&total);
    poignees.push(thread::spawn(move || {
        for _ in 0..1000 {
            *copie.lock().unwrap() += 1;
        }
    }));
}
for h in poignees {
    h.join().unwrap();
}
println!("total : {}", total.lock().unwrap());
println!("propriétaires : {}", Arc::strong_count(&total));
total : 4000
propriétaires : 1

Four threads, a thousand additions each, none lost. Over time, it looks like this:

 time ───────────────────────────────────────────────▶

 thread 1   ── lock() ████ guard ████ drop
 thread 2   ────── lock() ░░ waits ░░░ ████ guard ████ drop
                                       ▲
                                       └─ the lock changes hands

Each has its role. Arc answers “who owns the data”: everyone, until the last clone. Mutex answers “who may write to it right now”: whoever holds the guard.

What Mutex doesn’t solve

The poisoned lock. Why does lock() return a Result? Because a thread can panic while holding the lock, and leave the value half-modified:

let h = thread::spawn(move || {
    let mut g = copie.lock().unwrap();
    *g += 1;
    panic!("le thread s'arrête avec le verrou en main");
});
println!("join : erreur ? {}", h.join().is_err());
match total.lock() {
    Ok(g) => println!("valeur : {}", *g),
    Err(e) => println!("verrou empoisonné, valeur : {}", *e.into_inner()),
}
thread '<unnamed>' (537390) panicked at poison.rs:10:9:
le thread s'arrête avec le verrou en main
join : erreur ? true
verrou empoisonné, valeur : 1

The lock is indeed released (the guard is destroyed during the panic), but the Mutex is marked. The usual .unwrap() then propagates the panic to the other threads. When the value is still consistent, into_inner() gets it back.

The deadlock. Two locks, two threads, taken in opposite order:

thread::spawn(move || {
    let _ga = a1.lock().unwrap();
    thread::sleep(Duration::from_millis(50));
    let _gb = b1.lock().unwrap();
    tx1.send("thread 1").unwrap();
});

thread::spawn(move || {
    let _gb = b.lock().unwrap();
    thread::sleep(Duration::from_millis(50));
    let _ga = a.lock().unwrap();
    tx.send("thread 2").unwrap();
});

match rx.recv_timeout(Duration::from_millis(500)) {
    Ok(nom) => println!("{nom} a terminé"),
    Err(_) => println!("aucun thread n'a terminé après 500 ms : interblocage"),
}
aucun thread n'a terminé après 500 ms : interblocage
 thread 1   holds a ████████████████▶   wants b ░░░░░░░░░▶
 thread 2   holds b ████████████████▶   wants a ░░░░░░░░░▶

            each waits for the lock the other will never release

This program compiles with no error and no warning. No ownership rule is broken: every access is exclusive. Rust prevents the data race, not the deadlock. The cure is a convention: always take locks in the same order, and hold them for as short a time as possible.

What the picture hides

  • For a plain counter, an atomic type is enough. Arc<AtomicU32> with fetch_add(1, Ordering::Relaxed) gives the same total : 4000, with no lock and no guard. Measured: AtomicU32 is 4 bytes, Mutex<u32> is 16.
  • RwLock tells readers from the writer. Several read() at once, or a single write(). Checked: with two active readers, try_write() fails. It’s the borrowing rule, at run time and across threads.
  • Mutex doesn’t make everything shareable. Arc<Mutex<Rc<i32>>> is refused (E0277, “Rc<i32> cannot be sent between threads safely”): Mutex<T> is only Sync if T is Send, since the lock hands the value to each thread in turn.
  • The guard doesn’t change threads. MutexGuard is not Send: the lock must be released by the thread that took it. Moving it into another thread is refused at compile time.
  • thread::scope changes nothing about Sync. Borrowing a &Cell from a scoped thread gives the same error: a &Cell is not Send, precisely because Cell is not Sync.
  • Holding the guard too long is expensive. let g = m.lock().unwrap(); keeps the lock until the end of the block. *m.lock().unwrap() += 1; releases it at the end of the statement.
  • unsafe impl Send exists. That’s how Arc and Mutex themselves are declared in the standard library. Writing it yourself means promising the compiler what it can no longer check.

Going further

Questions fréquentesFrequently asked questions

Que signifie « cannot be shared between threads safely » ?What does "cannot be shared between threads safely" mean?

Le type nommé dans le message n'implémente pas Sync : il n'est pas sûr que plusieurs threads y accèdent en même temps à travers une référence partagée. C'est le cas de Cell et RefCell, qui modifient leur contenu à travers un & sans aucune synchronisation. L'erreur (E0277) apparaît dès qu'on tente de le partager, par exemple en déplaçant un Arc<Cell<i32>> dans thread::spawn. Le remède est de remplacer Cell par un type conçu pour le partage : Mutex, RwLock ou un type atomique.The type named in the message does not implement Sync: it is not safe for several threads to access it at the same time through a shared reference. That's the case for Cell and RefCell, which mutate their content through a & with no synchronization. The error (E0277) shows up as soon as you try to share it, for instance by moving an Arc<Cell<i32>> into thread::spawn. The cure is to replace Cell with a type built for sharing: Mutex, RwLock or an atomic type.

Quelle est la différence entre Send et Sync ?What is the difference between Send and Sync?

Send concerne le transfert : une valeur Send peut être déplacée dans un autre thread. Sync concerne le partage : un type T est Sync si une référence &T peut être envoyée à un autre thread, autrement dit si plusieurs threads peuvent lire la même valeur en même temps. Les deux sont indépendants. Cell<i32> est Send mais pas Sync : on peut la donner à un thread, pas la partager. MutexGuard est Sync mais pas Send. Rc n'est ni l'un ni l'autre. Ce sont des traits marqueurs, sans méthode, que le compilateur déduit automatiquement de la composition du type.Send is about transfer: a Send value can be moved into another thread. Sync is about sharing: a type T is Sync if a reference &T can be sent to another thread, in other words if several threads can read the same value at the same time. The two are independent. Cell<i32> is Send but not Sync: you can give it to a thread, not share it. MutexGuard is Sync but not Send. Rc is neither. They are marker traits, with no method, which the compiler derives automatically from what the type is made of.

Pourquoi Arc<Mutex<T>> et pas Arc tout seul ?Why Arc<Mutex<T>> and not Arc alone?

Parce qu'Arc ne donne qu'un accès en lecture. Il crée plusieurs propriétaires d'une même valeur, donc aucun ne peut avoir l'exclusivité qu'exige une modification : copie.push(4) sur un Arc<Vec<i32>> est refusé avec E0596, « cannot borrow data in an Arc as mutable ». Mutex ajoute ce qui manque : lock() bloque jusqu'à ce que le thread soit seul à tenir le verrou, puis rend un garde qui se comporte comme un &mut. Arc répond à « qui possède la donnée », Mutex à « qui a le droit d'y écrire maintenant ».Because Arc only gives read access. It creates several owners of the same value, so none can have the exclusivity a mutation requires: copie.push(4) on an Arc<Vec<i32>> is refused with E0596, "cannot borrow data in an Arc as mutable". Mutex adds what is missing: lock() blocks until the thread is the only one holding the lock, then returns a guard that behaves like a &mut. Arc answers "who owns the data", Mutex answers "who may write to it right now".

Qu'est-ce qu'un Mutex empoisonné, et pourquoi lock() rend-il un Result ?What is a poisoned Mutex, and why does lock() return a Result?

Si un thread panique pendant qu'il tient le verrou, la valeur protégée est peut-être dans un état intermédiaire. Le Mutex le signale : il devient « empoisonné », et tous les lock() suivants rendent Err(PoisonError). C'est la raison du Result, et du .unwrap() qu'on voit partout : il propage le panic aux autres threads. Quand la valeur reste utilisable, on la récupère avec into_inner() sur l'erreur. Mesuré avec rustc 1.100 : après un panic survenu juste après un += 1, le programme affiche « verrou empoisonné, valeur : 1 ».If a thread panics while it holds the lock, the protected value may be in an intermediate state. The Mutex reports it: it becomes "poisoned", and every later lock() returns Err(PoisonError). That's the reason for the Result, and for the .unwrap() you see everywhere: it propagates the panic to the other threads. When the value is still usable, you get it back with into_inner() on the error. Measured with rustc 1.100: after a panic right after a += 1, the program prints "verrou empoisonné, valeur : 1".

Rust empêche-t-il les interblocages (deadlocks) ?Does Rust prevent deadlocks?

Non. Rust garantit l'absence de course aux données (data race) : deux threads ne peuvent pas accéder à la même mémoire sans synchronisation si l'un des deux écrit. L'interblocage est un autre problème, qui ne viole aucune règle de possession : deux threads qui prennent deux verrous dans l'ordre inverse s'attendent l'un l'autre indéfiniment. Le programme compile sans avertissement. La prévention est une discipline : prendre les verrous toujours dans le même ordre, les tenir le moins longtemps possible, et éviter d'en tenir deux à la fois.No. Rust guarantees the absence of data races: two threads cannot access the same memory without synchronization if one of them writes. A deadlock is a different problem, which breaks no ownership rule: two threads taking two locks in opposite order wait for each other forever. The program compiles without a warning. Prevention is a discipline: always take locks in the same order, hold them for as short a time as possible, and avoid holding two at once.

RustSendSyncMutexArcConcurrenceModèle mental

← Tous les articlesAll articles