Scoped Threads

Normal threads cannot borrow from their environment:

  1. use std::thread;
  2. fn foo() {
  3.     let s = String::from("Hello");
  4.     thread::spawn(|| {
  5.         println!("Length: {}", s.len());
  6.     });
  7. }
  8. fn main() {
  9.     foo();
  10. }

However, you can use a scoped thread for this:

  1. use std::thread;
  2. fn foo() {
  3.     let s = String::from("Hello");
  4.     thread::scope(|scope| {
  5.         scope.spawn(|| {
  6.             println!("Length: {}", s.len());
  7.         });
  8.     });
  9. }
  10. fn main() {
  11.     foo();
  12. }

This slide should take about 13 minutes.

  • 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.