En bref. Lancer un thread, c’est confier une closure à un autre fil d’exécution, qui la fera tourner quand il voudra et aussi longtemps qu’il voudra. Si cette closure emprunte une variable locale, rien ne garantit que la variable existera encore. rustc le refuse avec E0373, closure may outlive the current function. Le mot-clé move règle le problème en changeant de modèle : la closure n’emprunte plus, elle emporte.
Le modèle en une phrase
thread::spawnn’attend pas : le thread peut vivre plus longtemps que la fonction qui le lance, donc il ne peut rien lui emprunter.movefait partir la donnée avec la closure, et elle appartient désormais au thread.
C’est le move du premier article, appliqué à une closure. Et quand on veut seulement prêter, thread::scope garantit que les threads finissent à temps : c’est le second onglet de l’animation.
In short. Starting a thread means handing a closure to another thread of execution, which will run it whenever it wants and for as long as it wants. If that closure borrows a local variable, nothing guarantees the variable will still exist. rustc refuses with E0373, closure may outlive the current function. The move keyword solves the problem by switching models: the closure no longer borrows, it takes the data along.
The model in one sentence
thread::spawndoesn’t wait: the thread may live longer than the function that starts it, so it can borrow nothing from it.movemakes the data leave with the closure, and it now belongs to the thread.
It’s the move from the first article, applied to a closure. And when you only want to lend, thread::scope guarantees the threads finish in time: that’s the animation’s second tab.
fn lancer() -> JoinHandle<()> {thread::spawn(|| println!("bonjour du thread"))}
thread::spawnlance le thread et rend la main aussitôt.lancer()se termine, le thread continue. Cette closure ne capture rien : elle ne dépend d'aucune variable locale, donc rien ne peut mal tourner.thread::spawnstarts the thread and returns right away.lancer()ends, the thread keeps going. This closure captures nothing: it depends on no local variable, so nothing can go wrong.- La closure lit
v: par défaut, elle capture une référence&v(8 octets). Maisvest libéré à la fin delancer(), et le thread peut tourner encore. rustc refuse : E0373, « closure may outlive the current function ».The closure readsv: by default, it captures a reference&v(8 bytes). Butvis freed at the end oflancer(), and the thread may still be running. rustc refuses: E0373, "closure may outlive the current function". movechange la capture : la closure ne prend plus&v, elle prendvlui-même (24 octets, leVecentier). La closure part dans le thread avec sa donnée.lancer()ne possède plus rien : le thread libéreravquand il aura fini.movechanges the capture: the closure no longer takes&v, it takesvitself (24 bytes, the wholeVec). The closure leaves for the thread with its data.lancer()owns nothing any more: the thread will freevwhen it is done.spawnrend unJoinHandle.join()bloque l'appelant jusqu'à la fin du thread et rend sa valeur de retour :Ok(6). Si le thread panique,join()rendErr. Sansjoin, le programme s'arrête à la fin demain, thread fini ou non.spawnreturns aJoinHandle.join()blocks the caller until the thread ends and returns its return value:Ok(6). If the thread panics,join()returnsErr. Withoutjoin, the program stops at the end ofmain, thread finished or not.
L’erreur : un thread qui emprunte
use std::thread;
fn main() {
let v = vec![1, 2, 3];
let h = thread::spawn(|| {
println!("somme : {}", v.iter().sum::<i32>());
});
h.join().unwrap();
}error[E0373]: closure may outlive the current function, but it borrows `v`, which is owned by the current function
--> emprunt.rs:5:27
|
5 | let h = thread::spawn(|| {
| ^^ may outlive borrowed value `v`
6 | println!("somme : {}", v.iter().sum::<i32>());
| - `v` is borrowed here
|
note: function requires argument type to outlive `'static`
--> emprunt.rs:5:13
|
5 | let h = thread::spawn(|| {
| _____________^
6 | | println!("somme : {}", v.iter().sum::<i32>());
7 | | });
| |______^
help: to force the closure to take ownership of `v` (and any other referenced variables), use the `move` keyword
|
5 | let h = thread::spawn(move || {
| ++++Le message contient tout. La closure ne fait que lire v, donc elle capture le minimum : une référence &v. Le propriétaire de v est la fonction courante. Et thread::spawn exige une closure 'static, c’est-à-dire, comme on l’a vu dans l’article sur 'static, une closure qui n’emprunte rien de temporaire.
Pourquoi : spawn n’attend pas
thread::spawn lance le thread et rend la main tout de suite. La fonction qui l’a appelé peut se terminer pendant que le thread tourne encore. Ce programme le montre, avec la version move qui, elle, compile :
fn lancer() -> JoinHandle<i32> {
let v = vec![1, 2, 3];
thread::spawn(move || {
thread::sleep(Duration::from_millis(50));
v.iter().sum::<i32>()
})
}
fn main() {
let h = lancer();
println!("lancer() est terminée, le thread tourne encore : {}", !h.is_finished());
println!("join : {:?}", h.join());
}lancer() est terminée, le thread tourne encore : true
join : Ok(6)lancer() est terminée, ses variables locales sont libérées, et le thread travaille toujours. Avec un emprunt, voici ce qui se passerait :
temps ───────────────────────────────────────────────▶
lancer() ├─ let v ─ spawn ─┤ fin : v est libéré
│
thread ├──────────── lit &v ───────────┤
▲
└─ &v pointe vers une valeur libéréeC’est la référence pendante que les lifetimes interdisent partout ailleurs. Entre threads, elle serait en plus impossible à reproduire d’une exécution à l’autre. rustc l’élimine avant.
Remarque que l’erreur tombe aussi dans main, et même si join() suit immédiatement. rustc ne raisonne pas sur ton intention : il lit la signature de spawn, et 'static y figure.
move : la closure emporte la donnée
let v = vec![1, 2, 3];
let h = thread::spawn(move || {
println!("somme : {}", v.iter().sum::<i32>());
});
h.join().unwrap();
println!("fin de main");somme : 6
fin de mainmove change ce que la closure capture. Une closure est une struct que le compilateur fabrique, avec un champ par variable capturée. On peut la mesurer :
let v = vec![1, 2, 3];
let rien = || 1 + 1;
let emprunt = || v.len();
println!("sans capture : {} octets", size_of_val(&rien));
println!("emprunt : {} octets", size_of_val(&emprunt));
let deplace = move || v.len();
println!("move : {} octets", size_of_val(&deplace));sans capture : 0 octets
emprunt : 8 octets
move : 24 octetsHuit octets : un pointeur vers v. Vingt-quatre : le Vec lui-même (pointeur, longueur, capacité), rangé dans la closure. Avec move, la closure ne dépend plus de rien d’extérieur : elle est 'static, et spawn l’accepte. La donnée voyage avec elle, et c’est le thread qui la libérera.
Le prix : la valeur est partie
let v = vec![1, 2, 3];
let h = thread::spawn(move || {
println!("somme : {}", v.iter().sum::<i32>());
});
println!("taille : {}", v.len());error[E0382]: borrow of moved value: `v`
--> apres_move.rs:8:29
|
4 | let v = vec![1, 2, 3];
| - move occurs because `v` has type `Vec<i32>`, which does not implement the `Copy` trait
5 | let h = thread::spawn(move || {
| ------- value moved into closure here
6 | println!("somme : {}", v.iter().sum::<i32>());
| - variable moved due to use in closure
7 | });
8 | println!("taille : {}", v.len());
| ^ value borrowed here after moveC’est l’erreur du premier article, mot pour mot : un seul propriétaire, et c’est maintenant le thread. Si main a encore besoin de la donnée, il y a trois réponses. Cloner avant le move :
let copie = v.clone();
let h = thread::spawn(move || copie.iter().sum::<i32>());
println!("taille : {}", v.len());
println!("join : {:?}", h.join());taille : 3
join : Ok(6)Partager avec Arc, qui ne copie qu’un pointeur. Ou prêter, avec thread::scope, plus bas.
join : attendre et récupérer
spawn rend un JoinHandle<T>, où T est le type de retour de la closure. join() bloque jusqu’à la fin du thread et rend un Result :
let h = thread::spawn(move || v.iter().sum::<i32>());
println!("main continue");
println!("join : {:?}", h.join());
let h = thread::spawn(|| {
let vide: Vec<i32> = Vec::new();
vide[0]
});
println!("join : erreur ? {}", h.join().is_err());
println!("fin de main");main continue
join : Ok(6)
thread '<unnamed>' (522905) panicked at join.rs:12:13:
index out of bounds: the len is 0 but the index is 0
join : erreur ? true
fin de mainUn panic dans un thread n’arrête que ce thread. main le reçoit sous forme de Err au moment du join, et décide quoi en faire.
Sans join, personne n’attend. Ce programme lance un thread qui dort 50 ms avant d’afficher la somme, et n’affiche que :
fin de mainQuand main se termine, le processus s’arrête, threads en cours compris.
thread::scope : prêter au lieu de donner
Quand le travail parallèle commence et finit dans la même fonction, déplacer est trop fort. thread::scope ouvre un bloc qui ne rend la main qu’une fois tous ses threads terminés :
let mut v = vec![1, 2, 3];
let (somme, taille) = thread::scope(|s| {
let a = s.spawn(|| v.iter().sum::<i32>());
let b = s.spawn(|| v.len());
(a.join().unwrap(), b.join().unwrap())
});
println!("somme : {somme}, taille : {taille}");
v.push(4);
println!("après le scope : {v:?}");somme : 6, taille : 3
après le scope : [1, 2, 3, 4]Aucun move, aucun clone, aucun Arc. Les deux closures empruntent v, et le compilateur l’accepte parce que la garantie est dans la construction elle-même : un thread scopé ne peut pas survivre au scope, donc pas à v.
main ├── let v ─────────────────────────── v.push(4) ──▶
┌ scope ─────────────────┐
a │ ├──── &v ─────┤ │
b │ ├──── &v ─────┤ │
└────────────────────────┘
▲
tous joints ici : les emprunts sont rendusEt puisque ce sont des emprunts, la règle de l’emprunt s’applique entre threads :
thread::scope(|s| {
s.spawn(|| v.push(4));
s.spawn(|| println!("taille : {}", v.len()));
});error[E0502]: cannot borrow `v` as immutable because it is also borrowed as mutable
--> scope_conflit.rs:7:17
|
5 | thread::scope(|s| {
| - has type `&'1 Scope<'1, '_>`
6 | s.spawn(|| v.push(4));
| ---------------------
| | | |
| | | first borrow occurs due to use of `v` in closure
| | mutable borrow occurs here
| argument requires that `v` is borrowed for `'1`
7 | s.spawn(|| println!("taille : {}", v.len()));
| ^^ - second borrow occurs due to use of `v` in closure
| |
| immutable borrow occurs hereUn thread qui écrit pendant qu’un autre lit : c’est la définition d’une course aux données. En Rust, c’est E0502, la même erreur que sans thread, détectée à la compilation. Un seul thread qui écrit, lui, passe : avec s.spawn(|| v.push(4)) seul dans le scope, le programme affiche après le scope : [1, 2, 3, 4].
Ce que l’image cache
movedéplace tout ce que la closure utilise. Pas demovevariable par variable. Pour ne donner qu’un clone ou une référence, on le crée avant (let copie = v.clone();) et c’est lui que la closure emporte.- Un type
Copyest copié, pas perdu. Aveclet n = 42;etmove || println!("{n}"),mainpeut encore liren: le programme affiche 42 des deux côtés. 'staticne veut pas dire « vit pour toujours ». Il veut dire « n’emprunte rien de temporaire ». UnVecdéplacé dans la closure satisfait'staticet sera libéré à la fin du thread.spawnexige aussiSend. Déplacer ne suffit pas toujours : unRcdéplacé dans un thread est refusé (E0277), comme on l’a vu avec Rc et Arc. C’est le sujet du prochain article.- Partager une donnée modifiable entre threads
spawndemandeArc<Mutex<T>>, croisé à la fin de l’article sur RefCell. - L’ordre d’exécution n’est pas garanti. Les barres de l’animation montrent un déroulement possible. Seuls
joinet la fin d’un scope fixent un « avant » et un « après ».
Pour aller plus loin
- Volume 7, numéro 01 de The Rust Loop, Threads & closures move, qui détaille le transfert de possession dans un thread et le thread scopé qui prête au lieu de déplacer (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), Rc et Arc (E0277), Cell et RefCell. - The Rust Book : utiliser des threads pour exécuter du code simultanément
- La bibliothèque standard :
thread::spawnetthread::scope - L’index des erreurs : E0373
The error: a thread that borrows
use std::thread;
fn main() {
let v = vec![1, 2, 3];
let h = thread::spawn(|| {
println!("somme : {}", v.iter().sum::<i32>());
});
h.join().unwrap();
}error[E0373]: closure may outlive the current function, but it borrows `v`, which is owned by the current function
--> emprunt.rs:5:27
|
5 | let h = thread::spawn(|| {
| ^^ may outlive borrowed value `v`
6 | println!("somme : {}", v.iter().sum::<i32>());
| - `v` is borrowed here
|
note: function requires argument type to outlive `'static`
--> emprunt.rs:5:13
|
5 | let h = thread::spawn(|| {
| _____________^
6 | | println!("somme : {}", v.iter().sum::<i32>());
7 | | });
| |______^
help: to force the closure to take ownership of `v` (and any other referenced variables), use the `move` keyword
|
5 | let h = thread::spawn(move || {
| ++++The message has it all. The closure only reads v, so it captures the minimum: a reference &v. The owner of v is the current function. And thread::spawn requires a 'static closure, which means, as seen in the article on 'static, a closure that borrows nothing temporary.
Why: spawn doesn’t wait
thread::spawn starts the thread and returns right away. The function that called it can end while the thread is still running. This program shows it, with the move version, which does compile:
fn lancer() -> JoinHandle<i32> {
let v = vec![1, 2, 3];
thread::spawn(move || {
thread::sleep(Duration::from_millis(50));
v.iter().sum::<i32>()
})
}
fn main() {
let h = lancer();
println!("lancer() est terminée, le thread tourne encore : {}", !h.is_finished());
println!("join : {:?}", h.join());
}lancer() est terminée, le thread tourne encore : true
join : Ok(6)lancer() has ended, its local variables are freed, and the thread is still working. With a borrow, here is what would happen:
time ────────────────────────────────────────────────▶
lancer() ├─ let v ─ spawn ─┤ end: v is freed
│
thread ├──────────── reads &v ─────────┤
▲
└─ &v points to a freed valueThat’s the dangling reference lifetimes forbid everywhere else. Across threads, it would also be impossible to reproduce from one run to the next. rustc eliminates it beforehand.
Note that the error also shows up in main, and even if join() follows immediately. rustc doesn’t reason about your intent: it reads the signature of spawn, and 'static is in it.
move: the closure takes the data along
let v = vec![1, 2, 3];
let h = thread::spawn(move || {
println!("somme : {}", v.iter().sum::<i32>());
});
h.join().unwrap();
println!("fin de main");somme : 6
fin de mainmove changes what the closure captures. A closure is a struct the compiler builds, with one field per captured variable. You can measure it:
let v = vec![1, 2, 3];
let rien = || 1 + 1;
let emprunt = || v.len();
println!("sans capture : {} octets", size_of_val(&rien));
println!("emprunt : {} octets", size_of_val(&emprunt));
let deplace = move || v.len();
println!("move : {} octets", size_of_val(&deplace));sans capture : 0 octets
emprunt : 8 octets
move : 24 octetsEight bytes: a pointer to v. Twenty-four: the Vec itself (pointer, length, capacity), stored inside the closure. With move, the closure no longer depends on anything outside: it is 'static, and spawn accepts it. The data travels with it, and the thread is the one that will free it.
The price: the value is gone
let v = vec![1, 2, 3];
let h = thread::spawn(move || {
println!("somme : {}", v.iter().sum::<i32>());
});
println!("taille : {}", v.len());error[E0382]: borrow of moved value: `v`
--> apres_move.rs:8:29
|
4 | let v = vec![1, 2, 3];
| - move occurs because `v` has type `Vec<i32>`, which does not implement the `Copy` trait
5 | let h = thread::spawn(move || {
| ------- value moved into closure here
6 | println!("somme : {}", v.iter().sum::<i32>());
| - variable moved due to use in closure
7 | });
8 | println!("taille : {}", v.len());
| ^ value borrowed here after moveIt’s the error from the first article, word for word: a single owner, and it’s now the thread. If main still needs the data, there are three answers. Clone before the move:
let copie = v.clone();
let h = thread::spawn(move || copie.iter().sum::<i32>());
println!("taille : {}", v.len());
println!("join : {:?}", h.join());taille : 3
join : Ok(6)Share with Arc, which only copies a pointer. Or lend, with thread::scope, further down.
join: wait and collect
spawn returns a JoinHandle<T>, where T is the closure’s return type. join() blocks until the thread ends and returns a Result:
let h = thread::spawn(move || v.iter().sum::<i32>());
println!("main continue");
println!("join : {:?}", h.join());
let h = thread::spawn(|| {
let vide: Vec<i32> = Vec::new();
vide[0]
});
println!("join : erreur ? {}", h.join().is_err());
println!("fin de main");main continue
join : Ok(6)
thread '<unnamed>' (522905) panicked at join.rs:12:13:
index out of bounds: the len is 0 but the index is 0
join : erreur ? true
fin de mainA panic in a thread only stops that thread. main receives it as an Err at the join, and decides what to do with it.
Without join, nobody waits. This program starts a thread that sleeps 50 ms before printing the sum, and prints only:
fin de mainWhen main ends, the process stops, running threads included.
thread::scope: lending instead of giving
When the parallel work begins and ends in the same function, moving is too strong. thread::scope opens a block that only returns once all its threads have finished:
let mut v = vec![1, 2, 3];
let (somme, taille) = thread::scope(|s| {
let a = s.spawn(|| v.iter().sum::<i32>());
let b = s.spawn(|| v.len());
(a.join().unwrap(), b.join().unwrap())
});
println!("somme : {somme}, taille : {taille}");
v.push(4);
println!("après le scope : {v:?}");somme : 6, taille : 3
après le scope : [1, 2, 3, 4]No move, no clone, no Arc. Both closures borrow v, and the compiler accepts it because the guarantee is in the construct itself: a scoped thread cannot outlive the scope, hence cannot outlive v.
main ├── let v ─────────────────────────── v.push(4) ──▶
┌ scope ─────────────────┐
a │ ├──── &v ─────┤ │
b │ ├──── &v ─────┤ │
└────────────────────────┘
▲
all joined here: the borrows are returnedAnd since these are borrows, the borrowing rule applies across threads:
thread::scope(|s| {
s.spawn(|| v.push(4));
s.spawn(|| println!("taille : {}", v.len()));
});error[E0502]: cannot borrow `v` as immutable because it is also borrowed as mutable
--> scope_conflit.rs:7:17
|
5 | thread::scope(|s| {
| - has type `&'1 Scope<'1, '_>`
6 | s.spawn(|| v.push(4));
| ---------------------
| | | |
| | | first borrow occurs due to use of `v` in closure
| | mutable borrow occurs here
| argument requires that `v` is borrowed for `'1`
7 | s.spawn(|| println!("taille : {}", v.len()));
| ^^ - second borrow occurs due to use of `v` in closure
| |
| immutable borrow occurs hereOne thread writing while another reads: that’s the definition of a data race. In Rust, it’s E0502, the same error as without threads, caught at compile time. A single writing thread goes through: with s.spawn(|| v.push(4)) alone in the scope, the program prints après le scope : [1, 2, 3, 4].
What the picture hides
movemoves everything the closure uses. There is no per-variablemove. To give away only a clone or a reference, create it first (let copie = v.clone();) and that’s what the closure takes along.- A
Copytype is copied, not lost. Withlet n = 42;andmove || println!("{n}"),maincan still readn: the program prints 42 on both sides. 'staticdoesn’t mean “lives forever”. It means “borrows nothing temporary”. AVecmoved into the closure satisfies'staticand will be freed when the thread ends.spawnalso requiresSend. Moving isn’t always enough: anRcmoved into a thread is refused (E0277), as seen with Rc and Arc. That’s the topic of the next article.- Sharing mutable data between
spawnthreads takesArc<Mutex<T>>, met at the end of the RefCell article. - Execution order isn’t guaranteed. The animation’s bars show one possible run. Only
joinand the end of a scope set a “before” and an “after”.
Going further
- Volume 7, issue 01 of The Rust Loop, Threads & move closures, which details transferring ownership into a thread and the scoped thread that lends instead of moving (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), Rc and Arc (E0277), Cell and RefCell. - The Rust Book: using threads to run code simultaneously
- The standard library:
thread::spawnandthread::scope - The error index: E0373