Rust newbie. Question about threading


#1

Hi,

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;
        std::thread::sleep(std::time::Duration::from_millis(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 || {
                tache.fonction(i);
            }));
            i +=5;
        }

        for child in children {
            child.join();
        }
    }

    for t in taches {
        println!("{}",&t.resultat);
    }
}

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 …


#2

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: http://aturon.github.io/crossbeam-doc/crossbeam/struct.Scope.html#method.spawn


#3

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

thanks for your answer.


#4

I meant that the underlying issue is really subtle and that even Rust experts make mistakes in this area: https://github.com/rust-lang/rust/issues/24292


#5

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