enaJ
enaJ

Reputation: 1655

Why does the Rust playground not produce different results for threads?

For the following sample code in Rust book concurrency chapter.

use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;

fn main() {
    let data = Arc::new(Mutex::new(vec![1, 2, 3]));

    for i in 0..3 {
        let data = data.clone();
        thread::spawn(move || {
            let mut data = data.lock().unwrap();
            data[0] += i;
            println!("{}", data[0]);
        });
    }

    thread::sleep(Duration::from_millis(50));
}

My friend and I separately ran this code on the Rust playground and always got the same order: 3, 4, 4, so it seems the threads are always started in the order of 2, 1, 0.

With multi-threaded programming, shouldn't we never know which thread will start first, as there is no fixed order of running the spawned threads? Is the Rust playground considered a single computer?

Upvotes: 1

Views: 298

Answers (1)

Steve Klabnik
Steve Klabnik

Reputation: 15529

This may not be the only thing at play here, but the playground does caching; if you don't change the code, it won't re-run it.

Upvotes: 5

Related Questions