Skip to content

Instantly share code, notes, and snippets.

@kriogenia
Created August 11, 2022 18:42
Show Gist options
  • Save kriogenia/256c9268b1fed170fde698e6218a4406 to your computer and use it in GitHub Desktop.
Save kriogenia/256c9268b1fed170fde698e6218a4406 to your computer and use it in GitHub Desktop.
Extra example of scoped threads
let mut a = vec![1, 2, 3];
let mut x = 0;
std::thread::scope(|s| {
s.spawn(|| {
println!("hello from the first scoped thread");
// We can borrow `a` here.
dbg!(&a);
});
s.spawn(|| {
println!("hello from the second scoped thread");
// We can even mutably borrow `x` here,
// because no other threads are using it.
x += a[0] + a[2];
});
println!("hello from the main thread");
});
// After the scope, we can modify and access our variables again:
a.push(4);
assert_eq!(x, a.len());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment