Arc examples do not run correctly on the Playground


#1

Hi Rustaceans,
it seems like Arc code samples from the documentation do not run correctly on the Playground on Safari (at least I only ever see about 2-6 output lines when I expect to see 10).
Or is the behaviour expected ?


#2

I think the main thread is exiting without waiting for all of the spawned threads to complete.


#3

Try this:

use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::thread;

fn main() {
    let val = Arc::new(AtomicUsize::new(5));
    
    let threads = (0..10).map(|_i| {
        let val = Arc::clone(&val);
    
        thread::spawn(move || {
            let v = val.fetch_add(1, Ordering::SeqCst);
            println!("{:?}", v);
        })
    }).collect::<Vec<_>>();
    threads.into_iter().for_each(|handle|{let _ = handle.join();});
}

#4

Thanks guys, for the explanation, and the working example.


#5

Does someone want to file a docs bug for fixing this example? We should make it better :slight_smile:


#6

also just discovered that sample from the new beta book about thread do not work as described either : https://doc.rust-lang.org/book/second-edition/ch16-01-threads.html

Nevermind, they actually do, but as Thread spawning takes much more time on my machine, I had to make the main thread run for much longer.