src/concurrency/threads/scoped.md
Normal threads cannot borrow from their environment:
# // Copyright 2024 Google LLC
# // SPDX-License-Identifier: Apache-2.0
#
use std::thread;
fn foo() {
let s = String::from("Hello");
thread::spawn(|| {
dbg!(s.len());
});
}
fn main() {
foo();
}
However, you can use a scoped thread for this:
# // Copyright 2024 Google LLC
# // SPDX-License-Identifier: Apache-2.0
#
use std::thread;
fn foo() {
let s = String::from("Hello");
thread::scope(|scope| {
scope.spawn(|| {
dbg!(s.len());
});
});
}
fn main() {
foo();
}
thread::scope function completes, all
the threads are guaranteed to be joined, so they can return borrowed data.