En bref. Box donne un seul propriétaire à une valeur sur le tas. Parfois il en faut plusieurs : une configuration lue par deux services, un nœud référencé par deux autres. Rc<T> le permet avec un compteur. Et le jour où l’un des propriétaires part dans un autre thread, rustc répond E0277, Rc<String> cannot be sent between threads safely. La réponse tient en une lettre de plus : Arc.
Le modèle en une phrase
Un
Rc<T>est une boîte à plusieurs propriétaires : chaque clone ajoute un propriétaire et incrémente un compteur, chaque disparition le décrémente, et la valeur est libérée quand le compteur retombe à zéro.
Trois conséquences suivent. Le partage impose la lecture seule. Le compteur de Rc n’est pas fait pour plusieurs threads, celui d’Arc l’est. Et un compteur qui ne retombe jamais à zéro est une fuite : c’est le cycle, second onglet de l’animation.
In short. Box gives a heap value a single owner. Sometimes you need several: a configuration read by two services, a node referenced by two others. Rc<T> allows it with a counter. And the day one of the owners leaves for another thread, rustc answers E0277, Rc<String> cannot be sent between threads safely. The answer is one letter longer: Arc.
The model in one sentence
An
Rc<T>is a box with several owners: each clone adds an owner and increments a counter, each disappearance decrements it, and the value is freed when the counter falls back to zero.
Three consequences follow. Sharing imposes read-only access. Rc’s counter isn’t made for several threads, Arc’s is. And a counter that never falls back to zero is a leak: that’s the cycle, the animation’s second tab.
let config = Rc::new(Config { nom: "prod".into() });Rc::strong_count(&config) // 1
Rc::newrange la valeur sur le tas, commeBox, avec un compteur à côté d'elle. Un propriétaire, compteur à 1.Rc::newstores the value on the heap, likeBox, with a counter next to it. One owner, counter at 1.Rc::clonene copie pas laConfig: il copie le pointeur et incrémente le compteur. Trois propriétaires, une seule valeur, à la même adresse (Rc::ptr_eqrendtrue).Rc::clonedoesn't copy theConfig: it copies the pointer and increments the counter. Three owners, a single value, at the same address (Rc::ptr_eqreturnstrue).- Chaque propriétaire qui disparaît décrémente le compteur.
workersort de sa portée,configest lâché : le compteur retombe à 1, et la valeur reste lisible parapi. Aucun propriétaire n'est le « vrai ».Each owner that goes away decrements the counter.workerleaves its scope,configis dropped: the counter falls back to 1, and the value stays readable throughapi. No owner is the "real" one. - Le dernier propriétaire disparaît, le compteur atteint 0, et
Droplibère la valeur : « Config libérée » s'affiche avant « fin de main ». Le moment dépend de l'exécution, plus de la seule lecture du code.The last owner goes away, the counter reaches 0, andDropfrees the value: "Config libérée" prints before "fin de main". The moment depends on execution, no longer on reading the code alone.
Quand un seul propriétaire ne suffit plus
struct Service { config: Box<Config> }
let config = Box::new(Config { nom: "prod".to_string() });
let api = Service { config };
let worker = Service { config };error[E0382]: use of moved value: `config`
--> partage_box.rs:8:28
|
6 | let config = Box::new(Config { nom: "prod".to_string() });
| ------ move occurs because `config` has type `Box<Config>`, which does not implement the `Copy` trait
7 | let api = Service { config };
| ------ value moved here
8 | let worker = Service { config };
| ^^^^^^ value used here after moveUne boîte a un propriétaire, et api l’a prise. On pourrait cloner la Config, mais on aurait deux configurations qui divergent à la première modification. On pourrait prêter &Config, mais il faudrait alors prouver qui vit le plus longtemps, avec des lifetimes dans chaque Service. Quand aucun propriétaire n’est clairement « le dernier », il reste à les compter.
Rc::clone ajoute un propriétaire
let config = Rc::new(Config { nom: "prod".to_string() });
let api = Service { config: Rc::clone(&config) };
{
let worker = Service { config: Rc::clone(&config) };
println!("même valeur : {}", Rc::ptr_eq(&api.config, &worker.config));
}
drop(config);
println!("lecture : {}", api.config.nom);
drop(api);
println!("fin de main");après new : 1
après api : 2
après worker : 3
même valeur : true
adresses : 0x102f6d4d0 0x102f6d4d0
worker sorti : 2
config lâché : 1
lecture : prod
Config libérée (prod)
fin de mainRc::clone ne touche pas à la Config. Il copie un pointeur de 8 octets et ajoute 1 au compteur rangé à côté de la valeur :
la pile le tas
┌────────────────┐
│ config ●─┼──────┐ ┌──────────────────────┐
├────────────────┤ ├─────▶│ compteur fort : 3 │
│ api.config ●─┼──────┤ ├──────────────────────┤
├────────────────┤ │ │ Config { nom: prod } │
│ worker.config●─┼──────┘ └──────────────────────┘
└────────────────┘ 0x…4d0
8 o chacunLa suite est la lecture de la sortie. worker sort de sa portée : 2. drop(config) lâche la variable d’origine : 1, et la valeur reste lisible par api, car aucun propriétaire n’est le « vrai ». drop(api) : 0, et Drop libère la valeur, avant « fin de main ».
Avec Box, le moment de la libération se lisait dans le code. Avec Rc, il dépend de l’ordre dans lequel les propriétaires disparaissent à l’exécution. C’est le prix du partage.
Partagé, donc en lecture seule : E0596
let a = Rc::new(vec![1, 2, 3]);
let b = Rc::clone(&a);
a.push(4);error[E0596]: cannot borrow data in an `Rc` as mutable
--> mutable.rs:6:5
|
6 | a.push(4);
| ^ cannot borrow as mutable
|
= help: trait `DerefMut` is required to modify through a dereference, but it is not implemented for `Rc<Vec<i32>>`C’est la règle de l’emprunt qui revient : plusieurs lecteurs, ou un seul écrivain. Un Rc a par construction plusieurs lecteurs, il ne donne donc que des &T. Rc::make_mut respecte la règle en clonant la valeur si elle est partagée :
let mut a = Rc::new(vec![1, 2, 3]);
let b = Rc::clone(&a);
Rc::make_mut(&mut a).push(4);[1, 2, 3, 4] [1, 2, 3]
même valeur : falsea a reçu sa propre copie, b garde l’ancienne : c’est de la copie à l’écriture. Pour que les deux voient la modification, il faut la mutabilité intérieure, Rc<RefCell<T>>, sujet du prochain numéro.
Entre threads : E0277, et Arc
let config = Rc::new(String::from("prod"));
let copie = Rc::clone(&config);
let h = thread::spawn(move || {
println!("{copie}");
});error[E0277]: `Rc<String>` cannot be sent between threads safely
--> thread_rc.rs:7:27
|
7 | let h = thread::spawn(move || {
| ------------- ^------
| | |
| _____________|_____________within this `{closure@thread_rc.rs:7:27: 7:34}`
| | |
| | required by a bound introduced by this call
8 | | println!("{copie}");
9 | | });
| |_____^ `Rc<String>` cannot be sent between threads safely
|
= help: within `{closure@thread_rc.rs:7:27: 7:34}`, the trait `Send` is not implemented for `Rc<String>`Le compteur d’un Rc est un entier ordinaire. Si deux threads font +1 au même instant, l’un des deux peut être perdu : le compteur atteint zéro trop tôt, et la valeur est libérée alors qu’un propriétaire la lit encore. Rust ne laisse pas ce programme exister : thread::spawn exige que ce qu’on lui donne soit Send, et Rc ne l’est pas. C’est une borne de trait comme une autre, vérifiée à la compilation.
let config = Arc::new(String::from("prod"));
let copie = Arc::clone(&config);
let h = thread::spawn(move || {
println!("dans le thread : {copie}, compteur {}", Arc::strong_count(&copie));
});
h.join().unwrap();
println!("après join : compteur {}", Arc::strong_count(&config));dans le thread : prod, compteur 2
après join : compteur 1Arc est le même modèle avec un compteur atomique : chaque +1 et chaque -1 est une opération indivisible, sûre depuis plusieurs threads. Même interface, même taille (8 octets). Le thread termine, sa copie disparaît, le compteur retombe à 1.
Le cycle : la fuite que Rust n’empêche pas
struct Noeud {
nom: &'static str,
autre: RefCell<Option<Rc<Noeud>>>,
}
let a = Rc::new(Noeud { nom: "a", autre: RefCell::new(None) });
let b = Rc::new(Noeud { nom: "b", autre: RefCell::new(Some(Rc::clone(&a))) });
*a.autre.borrow_mut() = Some(Rc::clone(&b));
println!("a : {} / b : {}", Rc::strong_count(&a), Rc::strong_count(&b));
println!("fin de main");a : 2 / b : 2
fin de mainNoeud implémente Drop et affiche « libéré ». Rien ne s’affiche. À la fin de main, les variables a et b disparaissent et chaque compteur passe de 2 à 1 : a est encore possédé par b, b par a.
┌──────── Rc ────────┐
│ ▼
┌─────────┐ ┌─────────┐
│ Noeud a │ │ Noeud b │ compteurs : 1 et 1
│ fort: 1 │ │ fort: 1 │ jamais 0, jamais libérés
└─────────┘ └─────────┘
▲ │
└──────── Rc ────────┘Le programme compile sans avertissement et ne viole aucune garantie : Rust promet qu’on ne lira jamais une mémoire invalide, pas qu’on rendra toute la mémoire. Un comptage de références ne voit pas les cycles.
Weak : connaître sans posséder
struct Noeud {
nom: &'static str,
enfant: RefCell<Option<Rc<Noeud>>>,
parent: RefCell<Weak<Noeud>>,
}
*parent.enfant.borrow_mut() = Some(Rc::clone(&enfant));
*enfant.parent.borrow_mut() = Rc::downgrade(&parent);parent : fort 1 faible 1
enfant : fort 2 faible 0
upgrade : parent
parent libéré
upgrade : personne
fin de main
enfant libéréUn Weak est un lien qui ne compte pas dans le compteur fort. Le parent possède l’enfant, l’enfant ne fait que connaître son parent. Le compteur fort du parent reste à 1 : drop(parent) le libère. Comme la valeur peut avoir disparu, un Weak ne se lit pas directement : upgrade() rend une Option, Some tant que le parent vit, None ensuite. L’absence est dans le type.
La question à se poser devant un graphe : qui possède qui ? Les liens de possession vont dans un sens (Rc), les liens de retour sont des Weak.
Ce que l’image cache
Rc::clone(&x)plutôt quex.clone(). Les deux font la même chose (compteur à 2,ptr_eqvrai). La forme longue signale au lecteur un clone bon marché, pas une copie profonde.Arcne rend pas le contenu modifiable. Il ne protège que le compteur. Pour écrire depuis plusieurs threads, il faut un verrou :Arc<Mutex<T>>.Arcpartout n’est pas gratuit. Les opérations atomiques coûtent plus cher qu’un+1. Dans un seul thread,Rcsuffit, et le compilateur te préviendra le jour où ce ne sera plus vrai.Rcn’est pas le premier réflexe. Un propriétaire et des emprunts&Tsuffisent le plus souvent, sans compteur ni allocation.Rcsert quand aucun propriétaire ne survit clairement aux autres.- Le compteur vit sur le tas, avec la valeur.
Rc<T>,Arc<T>etWeak<T>font 8 octets sur la pile ; les compteurs fort et faible sont rangés à côté de la valeur.
Pour aller plus loin
- Volume 6, numéro 02 de The Rust Loop, Rc / Arc, ou le partage par comptage de références, qui compte avec le programme, détaille les cycles et trois refus de terrain (lien en bas de page).
- Articles précédents : le move (E0382), l’emprunt (E0502), les slices, les lifetimes (E0106), l’élision,
'static, enums et match (E0004), Option et unwrap, newtype et type-state (E0599), Result et?(E0277), thiserror et anyhow (E0119), panic et invariants, traits et generics (E0369), dyn et vtable (E0038), règle de l’orphelin (E0117), Box et types récursifs (E0072). - The Rust Book :
Rc<T>, le pointeur à comptage de références - The Rust Book : les cycles de références peuvent fuir
- La bibliothèque standard :
std::sync::Arc
When a single owner is no longer enough
struct Service { config: Box<Config> }
let config = Box::new(Config { nom: "prod".to_string() });
let api = Service { config };
let worker = Service { config };error[E0382]: use of moved value: `config`
--> partage_box.rs:8:28
|
6 | let config = Box::new(Config { nom: "prod".to_string() });
| ------ move occurs because `config` has type `Box<Config>`, which does not implement the `Copy` trait
7 | let api = Service { config };
| ------ value moved here
8 | let worker = Service { config };
| ^^^^^^ value used here after moveA box has one owner, and api took it. You could clone the Config, but you’d have two configurations diverging at the first change. You could lend &Config, but then you’d have to prove who lives longest, with lifetimes in every Service. When no owner is clearly “the last one”, what’s left is counting them.
Rc::clone adds an owner
let config = Rc::new(Config { nom: "prod".to_string() });
let api = Service { config: Rc::clone(&config) };
{
let worker = Service { config: Rc::clone(&config) };
println!("même valeur : {}", Rc::ptr_eq(&api.config, &worker.config));
}
drop(config);
println!("lecture : {}", api.config.nom);
drop(api);
println!("fin de main");après new : 1
après api : 2
après worker : 3
même valeur : true
adresses : 0x102f6d4d0 0x102f6d4d0
worker sorti : 2
config lâché : 1
lecture : prod
Config libérée (prod)
fin de mainRc::clone doesn’t touch the Config. It copies an 8-byte pointer and adds 1 to the counter stored next to the value:
the stack the heap
┌────────────────┐
│ config ●─┼──────┐ ┌──────────────────────┐
├────────────────┤ ├─────▶│ strong count: 3 │
│ api.config ●─┼──────┤ ├──────────────────────┤
├────────────────┤ │ │ Config { nom: prod } │
│ worker.config●─┼──────┘ └──────────────────────┘
└────────────────┘ 0x…4d0
8 B eachThe rest is reading the output. worker leaves its scope: 2. drop(config) drops the original variable: 1, and the value stays readable through api, because no owner is the “real” one. drop(api): 0, and Drop frees the value, before “fin de main”.
With Box, the moment of release could be read in the code. With Rc, it depends on the order in which owners go away at runtime. That’s the price of sharing.
Shared, therefore read-only: E0596
let a = Rc::new(vec![1, 2, 3]);
let b = Rc::clone(&a);
a.push(4);error[E0596]: cannot borrow data in an `Rc` as mutable
--> mutable.rs:6:5
|
6 | a.push(4);
| ^ cannot borrow as mutable
|
= help: trait `DerefMut` is required to modify through a dereference, but it is not implemented for `Rc<Vec<i32>>`It’s the borrowing rule coming back: many readers, or a single writer. An Rc has several readers by construction, so it only hands out &T. Rc::make_mut respects the rule by cloning the value if it’s shared:
let mut a = Rc::new(vec![1, 2, 3]);
let b = Rc::clone(&a);
Rc::make_mut(&mut a).push(4);[1, 2, 3, 4] [1, 2, 3]
même valeur : falsea got its own copy, b keeps the old one: that’s copy-on-write. For both to see the change, you need interior mutability, Rc<RefCell<T>>, the subject of the next issue.
Across threads: E0277, and Arc
let config = Rc::new(String::from("prod"));
let copie = Rc::clone(&config);
let h = thread::spawn(move || {
println!("{copie}");
});error[E0277]: `Rc<String>` cannot be sent between threads safely
--> thread_rc.rs:7:27
|
7 | let h = thread::spawn(move || {
| ------------- ^------
| | |
| _____________|_____________within this `{closure@thread_rc.rs:7:27: 7:34}`
| | |
| | required by a bound introduced by this call
8 | | println!("{copie}");
9 | | });
| |_____^ `Rc<String>` cannot be sent between threads safely
|
= help: within `{closure@thread_rc.rs:7:27: 7:34}`, the trait `Send` is not implemented for `Rc<String>`An Rc’s counter is a plain integer. If two threads do +1 at the same instant, one of them can be lost: the counter reaches zero too early, and the value is freed while an owner is still reading it. Rust doesn’t let that program exist: thread::spawn requires what it’s given to be Send, and Rc isn’t. It’s a trait bound like any other, checked at compile time.
let config = Arc::new(String::from("prod"));
let copie = Arc::clone(&config);
let h = thread::spawn(move || {
println!("dans le thread : {copie}, compteur {}", Arc::strong_count(&copie));
});
h.join().unwrap();
println!("après join : compteur {}", Arc::strong_count(&config));dans le thread : prod, compteur 2
après join : compteur 1Arc is the same model with an atomic counter: each +1 and each -1 is an indivisible operation, safe from several threads. Same interface, same size (8 bytes). The thread finishes, its copy goes away, the counter falls back to 1.
The cycle: the leak Rust doesn’t prevent
struct Noeud {
nom: &'static str,
autre: RefCell<Option<Rc<Noeud>>>,
}
let a = Rc::new(Noeud { nom: "a", autre: RefCell::new(None) });
let b = Rc::new(Noeud { nom: "b", autre: RefCell::new(Some(Rc::clone(&a))) });
*a.autre.borrow_mut() = Some(Rc::clone(&b));
println!("a : {} / b : {}", Rc::strong_count(&a), Rc::strong_count(&b));
println!("fin de main");a : 2 / b : 2
fin de mainNoeud implements Drop and prints “libéré”. Nothing is printed. At the end of main, the variables a and b go away and each counter goes from 2 to 1: a is still owned by b, b by a.
┌──────── Rc ────────┐
│ ▼
┌─────────┐ ┌─────────┐
│ Noeud a │ │ Noeud b │ counters: 1 and 1
│ fort: 1 │ │ fort: 1 │ never 0, never freed
└─────────┘ └─────────┘
▲ │
└──────── Rc ────────┘The program compiles without a warning and breaks no guarantee: Rust promises you’ll never read invalid memory, not that you’ll give all memory back. Reference counting can’t see cycles.
Weak: knowing without owning
struct Noeud {
nom: &'static str,
enfant: RefCell<Option<Rc<Noeud>>>,
parent: RefCell<Weak<Noeud>>,
}
*parent.enfant.borrow_mut() = Some(Rc::clone(&enfant));
*enfant.parent.borrow_mut() = Rc::downgrade(&parent);parent : fort 1 faible 1
enfant : fort 2 faible 0
upgrade : parent
parent libéré
upgrade : personne
fin de main
enfant libéréA Weak is a link that doesn’t count in the strong counter. The parent owns the child, the child merely knows its parent. The parent’s strong count stays at 1: drop(parent) frees it. Since the value may be gone, a Weak can’t be read directly: upgrade() returns an Option, Some while the parent lives, None afterwards. Absence is in the type.
The question to ask in front of a graph: who owns whom? Ownership links go one way (Rc), back links are Weaks.
What the picture hides
Rc::clone(&x)rather thanx.clone(). Both do the same thing (counter at 2,ptr_eqtrue). The long form signals a cheap clone to the reader, not a deep copy.Arcdoesn’t make the content mutable. It only protects the counter. To write from several threads, you need a lock:Arc<Mutex<T>>.Arceverywhere isn’t free. Atomic operations cost more than a+1. In a single thread,Rcis enough, and the compiler will warn you the day that stops being true.Rcisn’t the first reflex. One owner and&Tborrows are enough most of the time, with no counter and no allocation.Rcis for when no owner clearly outlives the others.- The counter lives on the heap, with the value.
Rc<T>,Arc<T>andWeak<T>are 8 bytes on the stack; the strong and weak counters are stored next to the value.
Going further
- Volume 6, issue 02 of The Rust Loop, Rc / Arc, or sharing by reference counting, which counts along with the program, details cycles and three field refusals (link at the bottom of the page).
- Previous articles: move (E0382), borrowing (E0502), slices, lifetimes (E0106), elision,
'static, enums and match (E0004), Option and unwrap, newtype and type-state (E0599), Result and?(E0277), thiserror and anyhow (E0119), panic and invariants, traits and generics (E0369), dyn and the vtable (E0038), the orphan rule (E0117), Box and recursive types (E0072). - The Rust Book:
Rc<T>, the reference counted smart pointer - The Rust Book: reference cycles can leak memory
- The standard library:
std::sync::Arc