Scoped Threads

Normal threads cannot borrow from their environment:

1. use std::thread;

3. fn main() {
4. let s = String::from("Hello");

6. thread::spawn(|| {
7. println!("Length: {}", s.len());
8. });
9. }

However, you can use a scoped thread for this:

1. use std::thread;

3. fn main() {
4. let s = String::from("Hello");

6. thread::scope(|scope| {
7. scope.spawn(|| {
8. println!("Length: {}", s.len());
9. });
10. });
11. }
  • The reason for that is that when the thread::scope function completes, all the threads are guaranteed to be joined, so they can return borrowed data.
  • Normal Rust borrowing rules apply: you can either borrow mutably by one thread, or immutably by any number of threads.