Created
August 11, 2022 18:42
-
-
Save kriogenia/256c9268b1fed170fde698e6218a4406 to your computer and use it in GitHub Desktop.
Extra example of scoped threads
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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