gatewaynode
Gatewaynode

Gatewaynode

Rust scoped threads are back

gatewaynode's photo
gatewaynode
·Nov 5, 2022·

1 min read

Just wanted to share this slight modification on the documented example. I just added some dbg! calls and put the example in a main function, but now you can try this with copy and paste into your main.rs for a new cargo project.

use std::thread;

fn main() {
    let mut a = vec![1, 2, 3];
    let mut x = 0;

    dbg!(&x);

    thread::scope(|s| {
        s.spawn(|| {
            println!("hello from the first scoped thread");
            dbg!(&a);
        });
        s.spawn(|| {
            println!("hello from the second scoped thread");
            x += a[0] + a[2];
        });
        println!("hello from the main thread");
    });

    a.push(4);
    assert_eq!(x, a.len());
    dbg!(&a);
    dbg!(&x);
}

Further reading: wishawa.github.io/posts/thread-scoped-async

 
Share this