@@ -1,7 +1,7 @@
|
||||
# Scoped threads
|
||||
|
||||
All the lifetime issues we discussed so far have a common source:
|
||||
the spawned thread can outlive its parent.
|
||||
All the lifetime issues we discussed so far have a common source:
|
||||
the spawned thread can outlive its parent.\
|
||||
We can sidestep this issue by using **scoped threads**.
|
||||
|
||||
```rust
|
||||
@@ -26,16 +26,16 @@ Let's unpack what's happening.
|
||||
|
||||
## `scope`
|
||||
|
||||
The `std::thread::scope` function creates a new **scope**.
|
||||
`std::thread::scope` takes as input a closure, with a single argument: a `Scope` instance.
|
||||
The `std::thread::scope` function creates a new **scope**.\
|
||||
`std::thread::scope` takes as input a closure, with a single argument: a `Scope` instance.
|
||||
|
||||
## Scoped spawns
|
||||
|
||||
`Scope` exposes a `spawn` method.
|
||||
Unlike `std::thread::spawn`, all threads spawned using a `Scope` will be
|
||||
**automatically joined** when the scope ends.
|
||||
`Scope` exposes a `spawn` method.\
|
||||
Unlike `std::thread::spawn`, all threads spawned using a `Scope` will be
|
||||
**automatically joined** when the scope ends.
|
||||
|
||||
If we were to "translate" the previous example to `std::thread::spawn`,
|
||||
If we were to "translate" the previous example to `std::thread::spawn`,
|
||||
it'd look like this:
|
||||
|
||||
```rust
|
||||
@@ -61,13 +61,13 @@ println!("Here's v: {v:?}");
|
||||
|
||||
The translated example wouldn't compile, though: the compiler would complain
|
||||
that `&v` can't be used from our spawned threads since its lifetime isn't
|
||||
`'static`.
|
||||
`'static`.
|
||||
|
||||
That's not an issue with `std::thread::scope`—you can **safely borrow from the environment**.
|
||||
|
||||
In our example, `v` is created before the spawning points.
|
||||
It will only be dropped _after_ `scope` returns. At the same time,
|
||||
all threads spawned inside `scope` are guaranteed to finish _before_ `scope` returns,
|
||||
therefore there is no risk of having dangling references.
|
||||
therefore there is no risk of having dangling references.
|
||||
|
||||
The compiler won't complain!
|
||||
|
||||
Reference in New Issue
Block a user