Rust newbie. Question about threading



I’m learning Rust, and i try to understand threading.
I’ve write this very simple code :

use std::thread;

struct Tache {
    resultat : u64,

impl Tache {
    fn fonction(&mut self, nbre : u64) {
        self.resultat = nbre;

fn main() {
    let mut taches: Vec<Tache> = Vec::new();

    for j in 0..4 {
        let tache =  Tache{resultat : 0};
        taches.push( tache );

        let mut i: u64 = 10;
        let mut children = vec![];

        for mut tache in &mut taches {
            children.push(thread::spawn( move || {
            i +=5;

        for child in children {

    for t in taches {

but it doesn’t compile. (error: taches does not live long enough).
I’m sure it something stupid, but i can’t find how to do it correctly :slight_smile:

If someone could give me a hint …


No, it is not stupid at all! Rust assumes that a thread created with thread::spawn may outlive the parent thread, so it forbids to mutably access shared data.

To persuade the compiler that the threads are really joined before println!, you should use a scoped api from the crossbeam crate:


to be clear, when i’ve written “something stupid”, i was thinking of my code, not of Rust :slight_smile:

thanks for your answer.


I meant that the underlying issue is really subtle and that even Rust experts make mistakes in this area:


Out of curiosity is there a plan to introduce “fix” into core rust?