« RefCell already borrowed » : Cell et RefCell en Rust, le modèle mental de la mutabilité intérieure "RefCell already borrowed": Cell and RefCell in Rust, the mental model of interior mutability

RefCell applique la règle de l'emprunt à l'exécution : un registre à côté de la valeur compte les lecteurs et l'écrivain, et une violation devient un panic au lieu d'une erreur de compilation. Pourquoi E0594 derrière &self, ce que Cell fait autrement, quand écrire Rc<RefCell<T>>, et Mutex entre threads. Animation et sorties réelles de rustc.RefCell applies the borrowing rule at runtime: a registry next to the value counts readers and the writer, and a violation becomes a panic instead of a compile error. Why E0594 behind &self, what Cell does differently, when to write Rc<RefCell<T>>, and Mutex across threads. Animation and real rustc output.

AuteurAuthor
Ludovic Cleuet
ThèmeTopic
PointeursPointers
PubliéPublished

En bref. L’emprunt pose une règle : plusieurs lecteurs, ou un seul écrivain. Le compilateur la vérifie, et refuse tout ce qu’il ne sait pas prouver. Cell et RefCell permettent de modifier une valeur à travers une référence partagée &, en garantissant la règle autrement. Avec RefCell, la vérification a lieu à l’exécution, et une erreur ne s’appelle plus E0502 : elle s’appelle RefCell already borrowed, et c’est un panic.

Le modèle en une phrase

Un RefCell<T> range, à côté de la valeur, un registre d’emprunts : borrow() y inscrit un lecteur, borrow_mut() exige qu’il soit vide, et une violation de la règle arrête le programme au lieu d’arrêter la compilation.

La règle ne change pas, seul le moment de la vérification change. Et Cell évite la question : il ne prête jamais de référence, donc il n’a rien à vérifier. Le second onglet de l’animation compare les trois réponses.

In short. Borrowing sets a rule: many readers, or a single writer. The compiler checks it, and refuses whatever it can’t prove. Cell and RefCell let you modify a value through a shared & reference, by guaranteeing the rule another way. With RefCell, the check happens at runtime, and a mistake is no longer called E0502: it’s called RefCell already borrowed, and it’s a panic.

The model in one sentence

A RefCell<T> stores, next to the value, a borrow registry: borrow() registers a reader, borrow_mut() requires it to be empty, and breaking the rule stops the program instead of stopping the compilation.

The rule doesn’t change, only the moment of the check does. And Cell sidesteps the question: it never lends a reference, so it has nothing to check. The animation’s second tab compares the three answers.

let journal = RefCell::new(vec![String::from("démarrage")]);
RefCell<Vec<String>>RefCell<Vec<String>>la règle de l’emprunt, à l’exécutionthe borrowing rule, at runtimea : Refrendureleasedb : RefrendureleasedRefMutrendureleasedRefCellregistreregistrylibrefreeVec<String>le registre au fil du codethe registry over the code210écr.wr.0newborrow_mutaucun emprunt en cours : tout est permisno borrow in progress: anything goesregistre vide : 0 lecteur, 0 écrivainempty registry: 0 readers, 0 writers
  1. RefCell::new range la valeur avec un registre d'emprunts à côté d'elle. Personne n'a encore emprunté : le registre est vide.RefCell::new stores the value with a borrow registry next to it. Nobody has borrowed yet: the registry is empty.
  2. borrow() inscrit un lecteur et rend un Ref, un garde qui se désinscrit quand il disparaît. Des lecteurs, autant qu'on veut. Mais tant qu'ils vivent, try_borrow_mut() répond Err.borrow() registers a reader and returns a Ref, a guard that unregisters itself when it goes away. As many readers as you like. But while they live, try_borrow_mut() answers Err.
  3. borrow_mut() exige un registre vide. Il ne l'est pas : le programme, qui a compilé sans un avertissement, panique à cette ligne avec « RefCell already borrowed ». C'est E0502, reporté à l'exécution.borrow_mut() requires an empty registry. It isn't: the program, which compiled without a single warning, panics on this line with "RefCell already borrowed". It's E0502, postponed to runtime.
  4. Les lecteurs rendus, le registre retombe à zéro et l'écrivain passe, seul : pendant qu'il vit, même try_borrow() répond Err. La règle n'a pas changé, seulement le moment où elle est vérifiée.Once the readers are released, the registry falls back to zero and the writer goes through, alone: while it lives, even try_borrow() answers Err. The rule hasn't changed, only the moment it's checked.
RefCell<T> en Rust : la règle de l’emprunt vérifiée à l’exécution. borrow() inscrit un lecteur, borrow_mut() exige un registre vide ; sinon le programme panique avec « RefCell already borrowed ».RefCell<T> in Rust: the borrowing rule checked at runtime. borrow() registers a reader, borrow_mut() requires an empty registry; otherwise the program panics with "RefCell already borrowed".

Le problème : écrire derrière un &

struct Compteur {
    appels: u32,
}

impl Compteur {
    fn enregistrer(&self) {
        self.appels += 1;
    }
}
error[E0594]: cannot assign to `self.appels`, which is behind a `&` reference
 --> self_ref.rs:7:9
  |
7 |         self.appels += 1;
  |         ^^^^^^^^^^^^^^^^ `self` is a `&` reference, so it cannot be written to
  |
help: consider changing this to be a mutable reference
  |
6 |     fn enregistrer(&mut self) {
  |                     +++

Le conseil de rustc est le bon dans la plupart des cas. Mais &mut self a un coût : tout appelant doit détenir l’exclusivité sur le Compteur. Pour un compteur d’appels, un cache ou un journal, c’est disproportionné : vu de l’extérieur, la méthode ne fait que lire. On veut une méthode en &self dont un détail interne change. C’est la mutabilité intérieure.

Cell : copier, ne jamais prêter

struct Compteur {
    appels: Cell<u32>,
}

impl Compteur {
    fn enregistrer(&self) {
        self.appels.set(self.appels.get() + 1);
    }
}
appels : 2

Cell contourne la règle sans la violer. La règle de l’emprunt protège les références : personne ne doit lire une valeur pendant qu’un autre la modifie. Cell ne donne jamais de référence vers son contenu. get() en sort une copie, set() en range une nouvelle. Sans référence en circulation, rien ne peut être observé à moitié modifié.

Deux conséquences. Cell<u32> fait 4 octets, comme un u32 : aucun registre, aucun test, aucun panic possible. Et get() n’existe que pour les types Copy : sur un Cell<String>, rustc répond E0599, « the method get exists for struct Cell<String>, but its trait bounds were not satisfied », parce que String n’est pas Copy. Pour un Vec ou une String, on veut une référence vers l’intérieur. Il faut autre chose.

RefCell : la même règle, à l’exécution

let journal = RefCell::new(vec![String::from("démarrage")]);

let a = journal.borrow();
let b = journal.borrow();
println!("deux lecteurs  : {} et {}", a.len(), b.len());
println!("écrire ?       : {:?}", journal.try_borrow_mut().is_ok());
drop(a);
drop(b);

println!("écrire ?       : {:?}", journal.try_borrow_mut().is_ok());
journal.borrow_mut().push(String::from("requête"));
{
    let ecrivain = journal.borrow_mut();
    println!("lire ?         : {:?}", journal.try_borrow().is_ok());
    drop(ecrivain);
}
println!("journal        : {:?}", journal.borrow());
deux lecteurs  : 1 et 1
écrire ?       : false
écrire ?       : true
lire ?         : false
journal        : ["démarrage", "requête"]

RefCell prête des références, donc il les compte :

 journal : RefCell<Vec<String>>              32 octets
┌───────────────────┬──────────────────────────────┐
│ registre          │ valeur                       │
│ 2 lecteurs        │ Vec { ptr, len, cap }        │
└───────────────────┴──────────────────────────────┘
      ▲    ▲
      │    └── b : Ref     chaque garde se désinscrit
      └─────── a : Ref     quand il disparaît

 borrow_mut() ?  registre non vide → refus

borrow() rend un Ref, borrow_mut() un RefMut. Ce sont des gardes : ils se comportent comme &T et &mut T, et leur Drop met le registre à jour. La sortie dit le reste. Deux lecteurs vivants : écrire est refusé. Lecteurs rendus : écrire est accordé. Un écrivain vivant : même lire est refusé. C’est mot pour mot la règle du deuxième article.

Le panic : « RefCell already borrowed »

try_borrow_mut() rend un Result. borrow_mut(), lui, ne négocie pas :

let journal = RefCell::new(vec![String::from("démarrage")]);
let premier = journal.borrow();
journal.borrow_mut().push(String::from("requête"));
println!("{}", premier[0]);
thread 'main' (509474) panicked at panic_lecteur.rs:6:13:
RefCell already borrowed

Le même programme avec des références ordinaires ne compile pas :

error[E0502]: cannot borrow `journal` as mutable because it is also borrowed as immutable
 --> compile.rs:4:5
  |
3 |     let premier = &journal;
  |                   -------- immutable borrow occurs here
4 |     journal.push(String::from("requête"));
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
5 |     println!("{}", premier[0]);
  |                    ------- immutable borrow later used here

Même faute, même ligne, même diagnostic. La différence est le moment : E0502 te l’apprend avant la mise en production, le panic pendant. Et seulement si l’exécution passe par cette ligne : un RefCell mal utilisé dans une branche rare peut dormir longtemps.

Dans l’autre sens (un borrow() pendant qu’un écrivain vit), le message devient « RefCell already mutably borrowed ».

La forme la plus fréquente du piège est un emprunt qu’on ne voit pas :

for ligne in journal.borrow().iter() {
    if ligne == "démarrage" {
        journal.borrow_mut().push(String::from("prêt"));
    }
}
thread 'main' (509705) panicked at boucle.rs:7:21:
RefCell already borrowed

Le Ref créé dans l’en-tête du for vit pendant toute la boucle. Le réflexe à prendre : des emprunts courts, rendus avant d’appeler quoi que ce soit qui pourrait emprunter à son tour.

Rc<RefCell<T>> : partagé et modifiable

L’article précédent s’arrêtait là : un Rc a plusieurs propriétaires, donc son contenu est en lecture seule (E0596). RefCell fournit la moitié manquante :

let a = Rc::new(RefCell::new(vec![1, 2, 3]));
let b = Rc::clone(&a);
a.borrow_mut().push(4);
println!("{:?} {:?}", a.borrow(), b.borrow());
println!("même valeur : {}", Rc::ptr_eq(&a, &b));
[1, 2, 3, 4] [1, 2, 3, 4]
même valeur : true

Rc compte les propriétaires, RefCell compte les emprunts. Les deux propriétaires voient la modification, à la différence de Rc::make_mut, qui clonait.

Entre threads : Mutex

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

Le registre est un entier ordinaire, comme le compteur de Rc : deux threads pourraient s’y inscrire en même temps. RefCell n’est pas Sync, et le compilateur le sait. L’équivalent entre threads est un verrou :

let total = Arc::new(Mutex::new(0));
// quatre threads, chacun :
for _ in 0..1000 {
    *copie.lock().unwrap() += 1;
}
total : 4000

Mutex tient le même rôle que RefCell, avec une différence de comportement : en cas de conflit, le thread attend son tour au lieu de paniquer. Rc<RefCell<T>> dans un thread, Arc<Mutex<T>> entre plusieurs.

Ce que l’image cache

  • Rc<RefCell<T>> n’est pas un réflexe. Il réintroduit à l’exécution les erreurs que le compilateur éliminait. Un seul propriétaire qui passe des &mut en argument, ou un Vec avec des indices à la place de pointeurs, suffit souvent, et reste vérifié à la compilation.
  • try_borrow et try_borrow_mut rendent un Result. Quand un conflit est une situation normale et non un bug, on le traite au lieu de paniquer.
  • Cell ne se limite pas aux types Copy. Seul get() l’exige. set() et replace() déplacent la valeur entière, pour n’importe quel T.
  • Le prix se mesure. u32 et Cell<u32> : 4 octets. RefCell<u32> et Mutex<u32> : 16 octets (rustc 1.100, macOS arm64), plus un test à chaque emprunt.
  • Le mut de la déclaration ne dit plus tout. Un let journal sans mut peut changer s’il contient un RefCell. C’est le sens du mot « intérieure » : la mutabilité est dans le type, pas dans la liaison.

Pour aller plus loin

The problem: writing behind a &

struct Compteur {
    appels: u32,
}

impl Compteur {
    fn enregistrer(&self) {
        self.appels += 1;
    }
}
error[E0594]: cannot assign to `self.appels`, which is behind a `&` reference
 --> self_ref.rs:7:9
  |
7 |         self.appels += 1;
  |         ^^^^^^^^^^^^^^^^ `self` is a `&` reference, so it cannot be written to
  |
help: consider changing this to be a mutable reference
  |
6 |     fn enregistrer(&mut self) {
  |                     +++

rustc’s advice is the right one in most cases. But &mut self has a cost: every caller must hold exclusive access to the Compteur. For a call counter, a cache or a log, that’s out of proportion: seen from outside, the method only reads. You want a &self method with one internal detail that changes. That’s interior mutability.

Cell: copy, never lend

struct Compteur {
    appels: Cell<u32>,
}

impl Compteur {
    fn enregistrer(&self) {
        self.appels.set(self.appels.get() + 1);
    }
}
appels : 2

Cell gets around the rule without breaking it. The borrowing rule protects references: nobody may read a value while someone else modifies it. Cell never gives out a reference to its content. get() takes a copy out, set() stores a new one. With no reference in circulation, nothing can be observed half-modified.

Two consequences. Cell<u32> is 4 bytes, like a u32: no registry, no test, no possible panic. And get() only exists for Copy types: on a Cell<String>, rustc answers E0599, “the method get exists for struct Cell<String>, but its trait bounds were not satisfied”, because String isn’t Copy. For a Vec or a String, you want a reference to the inside. Something else is needed.

RefCell: the same rule, at runtime

let journal = RefCell::new(vec![String::from("démarrage")]);

let a = journal.borrow();
let b = journal.borrow();
println!("deux lecteurs  : {} et {}", a.len(), b.len());
println!("écrire ?       : {:?}", journal.try_borrow_mut().is_ok());
drop(a);
drop(b);

println!("écrire ?       : {:?}", journal.try_borrow_mut().is_ok());
journal.borrow_mut().push(String::from("requête"));
{
    let ecrivain = journal.borrow_mut();
    println!("lire ?         : {:?}", journal.try_borrow().is_ok());
    drop(ecrivain);
}
println!("journal        : {:?}", journal.borrow());
deux lecteurs  : 1 et 1
écrire ?       : false
écrire ?       : true
lire ?         : false
journal        : ["démarrage", "requête"]

RefCell lends references, so it counts them:

 journal: RefCell<Vec<String>>               32 bytes
┌───────────────────┬──────────────────────────────┐
│ registry          │ value                        │
│ 2 readers         │ Vec { ptr, len, cap }        │
└───────────────────┴──────────────────────────────┘
      ▲    ▲
      │    └── b: Ref      each guard unregisters
      └─────── a: Ref      itself when it goes away

 borrow_mut()?  registry not empty → refused

borrow() returns a Ref, borrow_mut() a RefMut. They are guards: they behave like &T and &mut T, and their Drop updates the registry. The output says the rest. Two living readers: writing is refused. Readers released: writing is granted. A living writer: even reading is refused. It’s word for word the rule from the second article.

The panic: “RefCell already borrowed”

try_borrow_mut() returns a Result. borrow_mut() doesn’t negotiate:

let journal = RefCell::new(vec![String::from("démarrage")]);
let premier = journal.borrow();
journal.borrow_mut().push(String::from("requête"));
println!("{}", premier[0]);
thread 'main' (509474) panicked at panic_lecteur.rs:6:13:
RefCell already borrowed

The same program with ordinary references doesn’t compile:

error[E0502]: cannot borrow `journal` as mutable because it is also borrowed as immutable
 --> compile.rs:4:5
  |
3 |     let premier = &journal;
  |                   -------- immutable borrow occurs here
4 |     journal.push(String::from("requête"));
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
5 |     println!("{}", premier[0]);
  |                    ------- immutable borrow later used here

Same mistake, same line, same diagnosis. The difference is the moment: E0502 tells you before going to production, the panic during. And only if execution goes through that line: a misused RefCell in a rare branch can sleep for a long time.

The other way round (a borrow() while a writer lives), the message becomes “RefCell already mutably borrowed”.

The most frequent form of the trap is a borrow you don’t see:

for ligne in journal.borrow().iter() {
    if ligne == "démarrage" {
        journal.borrow_mut().push(String::from("prêt"));
    }
}
thread 'main' (509705) panicked at boucle.rs:7:21:
RefCell already borrowed

The Ref created in the for header lives for the whole loop. The reflex to build: short borrows, released before calling anything that might borrow in turn.

Rc<RefCell<T>>: shared and mutable

The previous article stopped there: an Rc has several owners, so its content is read-only (E0596). RefCell provides the missing half:

let a = Rc::new(RefCell::new(vec![1, 2, 3]));
let b = Rc::clone(&a);
a.borrow_mut().push(4);
println!("{:?} {:?}", a.borrow(), b.borrow());
println!("même valeur : {}", Rc::ptr_eq(&a, &b));
[1, 2, 3, 4] [1, 2, 3, 4]
même valeur : true

Rc counts owners, RefCell counts borrows. Both owners see the change, unlike Rc::make_mut, which cloned.

Across threads: Mutex

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

The registry is a plain integer, like Rc’s counter: two threads could register at the same time. RefCell isn’t Sync, and the compiler knows it. The cross-thread equivalent is a lock:

let total = Arc::new(Mutex::new(0));
// four threads, each:
for _ in 0..1000 {
    *copie.lock().unwrap() += 1;
}
total : 4000

Mutex plays the same role as RefCell, with one difference in behaviour: on a conflict, the thread waits its turn instead of panicking. Rc<RefCell<T>> within one thread, Arc<Mutex<T>> across several.

What the picture hides

  • Rc<RefCell<T>> isn’t a reflex. It brings back at runtime the mistakes the compiler used to eliminate. A single owner passing &mut as arguments, or a Vec with indices instead of pointers, is often enough, and stays checked at compile time.
  • try_borrow and try_borrow_mut return a Result. When a conflict is a normal situation and not a bug, you handle it instead of panicking.
  • Cell isn’t limited to Copy types. Only get() requires it. set() and replace() move the whole value, for any T.
  • The price can be measured. u32 and Cell<u32>: 4 bytes. RefCell<u32> and Mutex<u32>: 16 bytes (rustc 1.100, macOS arm64), plus a test on each borrow.
  • The declaration’s mut no longer tells everything. A let journal without mut can change if it contains a RefCell. That’s the meaning of “interior”: the mutability is in the type, not in the binding.

Going further

Questions fréquentesFrequently asked questions

Que signifie « RefCell already borrowed » ?What does "RefCell already borrowed" mean?

C'est un panic, pas une erreur de compilation. Tu as appelé borrow_mut() sur un RefCell alors qu'un emprunt obtenu par borrow() (ou un autre borrow_mut()) était encore vivant. RefCell vérifie à l'exécution la règle « plusieurs lecteurs ou un seul écrivain », et arrête le programme quand elle est violée. Correctif : raccourcir la vie du premier emprunt (un bloc, un drop, ou copier la donnée dont tu as besoin avant d'écrire). La variante « RefCell already mutably borrowed » signale l'inverse : un borrow() pendant qu'un écrivain vit.It's a panic, not a compile error. You called borrow_mut() on a RefCell while a borrow obtained through borrow() (or another borrow_mut()) was still alive. RefCell checks the "many readers or one writer" rule at runtime, and stops the program when it's broken. Fix: shorten the life of the first borrow (a block, a drop, or copy the data you need before writing). The "RefCell already mutably borrowed" variant signals the reverse: a borrow() while a writer lives.

Quelle différence entre Cell et RefCell ?What's the difference between Cell and RefCell?

Cell ne prête jamais de référence vers son contenu : get() en sort une copie, set() en range une nouvelle. Sans référence, aucune règle à vérifier : pas de surcoût (Cell<u32> fait 4 octets) et aucun panic possible. RefCell prête des références (borrow, borrow_mut), donc il doit les compter : un registre en plus (RefCell<u32> fait 16 octets), un test à chaque emprunt, et un panic en cas de conflit. Cell pour les petites valeurs Copy (compteurs, drapeaux), RefCell quand il faut une référence vers l'intérieur (Vec, String, struct).Cell never lends a reference to its content: get() takes a copy out, set() stores a new one. With no reference, there is no rule to check: no overhead (Cell<u32> is 4 bytes) and no possible panic. RefCell lends references (borrow, borrow_mut), so it has to count them: an extra registry (RefCell<u32> is 16 bytes), a test on each borrow, and a panic on a conflict. Cell for small Copy values (counters, flags), RefCell when you need a reference to the inside (Vec, String, struct).

Qu'est-ce que la mutabilité intérieure, et pourquoi E0594 ?What is interior mutability, and why E0594?

E0594 (« cannot assign to `self.appels`, which is behind a `&` reference ») dit qu'une référence partagée & ne permet pas d'écrire. La mutabilité intérieure est le moyen de modifier quand même une valeur à travers un & : le type (Cell, RefCell, Mutex, les atomiques) garantit lui-même que la modification est sûre, à la place du compilateur. On s'en sert pour un cache, un compteur d'appels, un journal : un état interne qui change sans que la méthode ait besoin de &mut self.E0594 ("cannot assign to `self.appels`, which is behind a `&` reference") says that a shared & reference doesn't allow writing. Interior mutability is the way to modify a value through a & anyway: the type (Cell, RefCell, Mutex, the atomics) guarantees by itself that the modification is safe, instead of the compiler. It's used for a cache, a call counter, a log: internal state that changes without the method needing &mut self.

Pourquoi écrit-on Rc<RefCell<T>> ?Why do people write Rc<RefCell<T>>?

Parce que chacun apporte une moitié. Rc donne plusieurs propriétaires, mais en lecture seule. RefCell rend le contenu modifiable à travers une référence partagée. Ensemble : une valeur partagée que chaque propriétaire peut modifier, et tous voient le changement. Le prix est que la règle de l'emprunt n'est plus vérifiée à la compilation : une erreur devient un panic. Avant d'y recourir, vérifie qu'un seul propriétaire avec des &mut passés en argument, ou un Vec avec des indices, ne suffit pas.Because each brings one half. Rc gives several owners, but read-only. RefCell makes the content mutable through a shared reference. Together: a shared value every owner can modify, and all of them see the change. The price is that the borrowing rule is no longer checked at compile time: a mistake becomes a panic. Before reaching for it, check that a single owner with &mut passed as arguments, or a Vec with indices, isn't enough.

Peut-on utiliser RefCell entre plusieurs threads ?Can RefCell be used across several threads?

Non. Le registre d'un RefCell est un entier ordinaire, que deux threads pourraient modifier en même temps. RefCell n'implémente pas Sync, et rustc refuse Arc<RefCell<T>> dans thread::spawn avec E0277, « `RefCell<i32>` cannot be shared between threads safely ». L'équivalent entre threads est Mutex<T> (ou RwLock<T>) : même idée, mais en cas de conflit le thread attend son tour au lieu de paniquer. On écrit Arc<Mutex<T>> là où on écrivait Rc<RefCell<T>>.No. A RefCell's registry is a plain integer, which two threads could modify at the same time. RefCell doesn't implement Sync, and rustc refuses Arc<RefCell<T>> in thread::spawn with E0277, "`RefCell<i32>` cannot be shared between threads safely". The cross-thread equivalent is Mutex<T> (or RwLock<T>): same idea, but on a conflict the thread waits its turn instead of panicking. You write Arc<Mutex<T>> where you wrote Rc<RefCell<T>>.

RustRefCellCellInterior mutabilitySmart pointersModèle mental

← Tous les articlesAll articles