« closure may outlive the current function » : threads et closures move en Rust (E0373) "closure may outlive the current function": threads and move closures in Rust (E0373)

thread::spawn rend la main aussitôt : le thread peut vivre plus longtemps que la fonction qui le lance, donc une closure qui emprunte une variable locale est refusée (E0373). Ce que move change, pourquoi la valeur est ensuite perdue pour l'appelant (E0382), ce que rend join(), et thread::scope qui prête au lieu de donner. Animation et sorties réelles de rustc.thread::spawn returns right away: the thread may live longer than the function that starts it, so a closure that borrows a local variable is refused (E0373). What move changes, why the value is then lost to the caller (E0382), what join() returns, and thread::scope, which lends instead of giving. Animation and real rustc output.

AuteurAuthor
Ludovic Cleuet
ThèmeTopic
ConcurrenceConcurrency
PubliéPublished

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::spawn n’attend pas : le thread peut vivre plus longtemps que la fonction qui le lance, donc il ne peut rien lui emprunter. move fait 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::spawn doesn’t wait: the thread may live longer than the function that starts it, so it can borrow nothing from it. move makes 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::spawnthread::spawnle thread peut survivre à la fonctionthe thread may outlive the function|| println!(…)capturecapturesriennothingtaillesize0 octet0 bytes’static ?’static?ouiyesdurées de vie, dans le tempslifetimes, over timemainlancer()threadfin de lancer()end of lancer()possèdeownsemprunteborrowshors jeuout of playspawn n’attend pas : le thread dépasse la fonction qui le lancespawn does not wait: the thread outlasts the function that starts itsortie : lancer() est terminée · bonjour du threadoutput: lancer() est terminée · bonjour du thread
  1. thread::spawn lance 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::spawn starts 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.
  2. La closure lit v : par défaut, elle capture une référence &v (8 octets). Mais v est libéré à la fin de lancer(), et le thread peut tourner encore. rustc refuse : E0373, « closure may outlive the current function ».The closure reads v: by default, it captures a reference &v (8 bytes). But v is freed at the end of lancer(), and the thread may still be running. rustc refuses: E0373, "closure may outlive the current function".
  3. move change la capture : la closure ne prend plus &v, elle prend v lui-même (24 octets, le Vec entier). La closure part dans le thread avec sa donnée. lancer() ne possède plus rien : le thread libérera v quand il aura fini.move changes the capture: the closure no longer takes &v, it takes v itself (24 bytes, the whole Vec). The closure leaves for the thread with its data. lancer() owns nothing any more: the thread will free v when it is done.
  4. spawn rend un JoinHandle. join() bloque l'appelant jusqu'à la fin du thread et rend sa valeur de retour : Ok(6). Si le thread panique, join() rend Err. Sans join, le programme s'arrête à la fin de main, thread fini ou non.spawn returns a JoinHandle. join() blocks the caller until the thread ends and returns its return value: Ok(6). If the thread panics, join() returns Err. Without join, the program stops at the end of main, thread finished or not.
Threads et closures move en Rust : thread::spawn rend la main aussitôt, donc une closure qui emprunte une variable locale est refusée (E0373). Avec move, la valeur part dans la closure et appartient au thread ; join() attend sa fin et rend son résultat.Threads and move closures in Rust: thread::spawn returns right away, so a closure that borrows a local variable is refused (E0373). With move, the value goes into the closure and belongs to the thread; join() waits for it to end and returns its result.

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ée

C’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 main

move 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 octets

Huit 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 move

C’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 main

Un 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 main

Quand 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 rendus

Et 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 here

Un 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

  • move déplace tout ce que la closure utilise. Pas de move variable 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 Copy est copié, pas perdu. Avec let n = 42; et move || println!("{n}"), main peut encore lire n : le programme affiche 42 des deux côtés.
  • 'static ne veut pas dire « vit pour toujours ». Il veut dire « n’emprunte rien de temporaire ». Un Vec déplacé dans la closure satisfait 'static et sera libéré à la fin du thread.
  • spawn exige aussi Send. Déplacer ne suffit pas toujours : un Rc dé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 spawn demande Arc<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 join et la fin d’un scope fixent un « avant » et un « après ».

Pour aller plus loin

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 value

That’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 main

move 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 octets

Eight 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 move

It’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 main

A 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 main

When 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 returned

And 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 here

One 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

  • move moves everything the closure uses. There is no per-variable move. 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 Copy type is copied, not lost. With let n = 42; and move || println!("{n}"), main can still read n: the program prints 42 on both sides.
  • 'static doesn’t mean “lives forever”. It means “borrows nothing temporary”. A Vec moved into the closure satisfies 'static and will be freed when the thread ends.
  • spawn also requires Send. Moving isn’t always enough: an Rc moved into a thread is refused (E0277), as seen with Rc and Arc. That’s the topic of the next article.
  • Sharing mutable data between spawn threads takes Arc<Mutex<T>>, met at the end of the RefCell article.
  • Execution order isn’t guaranteed. The animation’s bars show one possible run. Only join and the end of a scope set a “before” and an “after”.

Going further

Questions fréquentesFrequently asked questions

Que signifie E0373, « closure may outlive the current function » ?What does E0373, "closure may outlive the current function", mean?

La closure emprunte une variable locale, et tu la passes à quelque chose qui peut l'exécuter après la fin de la fonction, le plus souvent thread::spawn. À ce moment-là, la variable serait libérée et la référence pointerait vers rien. rustc refuse à la compilation. Le correctif proposé est le bon dans la plupart des cas : écrire move devant la closure, pour qu'elle prenne possession de la variable au lieu de l'emprunter.The closure borrows a local variable, and you pass it to something that may run it after the function has ended, most often thread::spawn. At that point the variable would be freed and the reference would point to nothing. rustc refuses at compile time. The suggested fix is the right one in most cases: write move in front of the closure, so that it takes ownership of the variable instead of borrowing it.

Que fait le mot-clé move devant une closure ?What does the move keyword do in front of a closure?

Il change la façon dont la closure capture son environnement. Sans move, elle capture le moins possible : une référence & si elle ne fait que lire. Avec move, elle prend possession de chaque variable qu'elle utilise : la valeur est déplacée dans la closure (ou copiée, pour un type Copy comme i32). Mesuré avec rustc 1.100 : une closure qui emprunte un Vec fait 8 octets, la même avec move en fait 24, la taille du Vec lui-même.It changes how the closure captures its environment. Without move, it captures as little as possible: a & reference if it only reads. With move, it takes ownership of every variable it uses: the value is moved into the closure (or copied, for a Copy type such as i32). Measured with rustc 1.100: a closure that borrows a Vec is 8 bytes, the same one with move is 24, the size of the Vec itself.

Pourquoi E0373 alors que j'appelle join() juste après ?Why E0373 when I call join() right after?

Parce que rustc ne lit pas ton intention, il lit la signature de thread::spawn, qui exige une closure 'static : une closure qui n'emprunte rien de temporaire. Le fait que tu appelles join() deux lignes plus bas n'apparaît nulle part dans les types, et rien n'empêcherait de l'oublier ou de le retirer. Pour emprunter avec la garantie que les threads sont joints à temps, utilise thread::scope : c'est le bloc lui-même qui joint, donc le compilateur peut s'y fier.Because rustc doesn't read your intent, it reads the signature of thread::spawn, which requires a 'static closure: a closure that borrows nothing temporary. The fact that you call join() two lines later appears nowhere in the types, and nothing would stop you from forgetting or removing it. To borrow with the guarantee that threads are joined in time, use thread::scope: the block itself does the joining, so the compiler can rely on it.

Comment utiliser une variable dans un thread et la garder dans main ?How do I use a variable in a thread and keep it in main?

Trois moyens. Cloner avant le move (let copie = v.clone();) : simple, mais les données sont copiées. Partager avec Arc : Arc::clone ne copie qu'un pointeur, et chaque thread possède sa part. Ou thread::scope, qui laisse les threads emprunter la variable sans la déplacer : après le scope, elle est toujours à main. Sans l'un des trois, rustc répond E0382, « borrow of moved value », dès que main touche à la variable après le spawn.Three ways. Clone before the move (let copie = v.clone();): simple, but the data is copied. Share with Arc: Arc::clone only copies a pointer, and every thread owns its share. Or thread::scope, which lets threads borrow the variable without moving it: after the scope, it still belongs to main. Without one of the three, rustc answers E0382, "borrow of moved value", as soon as main touches the variable after the spawn.

Qu'est-ce que thread::scope, et quand le préférer à thread::spawn ?What is thread::scope, and when should I prefer it to thread::spawn?

thread::scope ouvre un bloc dans lequel on lance des threads avec s.spawn(...), et ne rend la main qu'une fois tous ces threads terminés. Comme ils ne peuvent pas survivre au bloc, ils ont le droit d'emprunter les variables locales, sans move, sans clone et sans Arc. Préfère-le quand le travail parallèle a un début et une fin dans la même fonction (découper un calcul, traiter des morceaux d'un tableau). Garde thread::spawn pour un thread qui doit vivre au-delà de la fonction : un worker, un serveur, une tâche de fond.thread::scope opens a block in which you start threads with s.spawn(...), and only returns once all those threads have finished. Since they cannot outlive the block, they are allowed to borrow local variables, with no move, no clone and no Arc. Prefer it when the parallel work begins and ends in the same function (splitting a computation, processing chunks of an array). Keep thread::spawn for a thread that must live beyond the function: a worker, a server, a background task.

RustThreadsmoveClosuresConcurrenceModèle mental

← Tous les articlesAll articles