Skip to content

Commit 9f8946c

Browse files
Add a section on scoped threads
1 parent 12312fa commit 9f8946c

File tree

1 file changed

+45
-1
lines changed

1 file changed

+45
-1
lines changed

posts/2022-08-11-Rust-1.63.0.md

Lines changed: 45 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,50 @@ Please [report] any bugs you might come across!
2828

2929
## What's in 1.63.0 stable
3030

31+
### Scoped threads
32+
33+
Rust code could launch new threads with `std::thread::spawn` since 1.0, but this
34+
function bounds its closure with `'static`. Roughly, this means that threads
35+
currently must have ownership of any arguments passed into their closure; you
36+
can't pass borrowed data into a thread. In cases where the threads are expected
37+
to exit by the end of the function (by being `join()`'d), this isn't strictly
38+
necessary and can require workarounds like placing the data in an [`Arc`].
39+
40+
Now, with 1.63.0, the standard library is adding *scoped* threads, which allow
41+
spawning a thread borrowing from the local stack frame. The
42+
[`std::thread::scope`] API provides the necessary guarantee that any spawned threads
43+
will have exited prior to itself returning, which allows for safely borrowing
44+
data. Here's an example:
45+
46+
```rust
47+
let mut a = vec![1, 2, 3];
48+
let mut x = 0;
49+
50+
std::thread::scope(|s| {
51+
s.spawn(|| {
52+
println!("hello from the first scoped thread");
53+
// We can borrow `a` here.
54+
dbg!(&a);
55+
});
56+
s.spawn(|| {
57+
println!("hello from the second scoped thread");
58+
// We can even mutably borrow `x` here,
59+
// because no other threads are using it.
60+
x += a[0] + a[2];
61+
});
62+
println!("hello from the main thread");
63+
});
64+
65+
// After the scope, we can modify and access our variables again:
66+
a.push(4);
67+
assert_eq!(x, a.len());
68+
```
69+
70+
[`std::thread::scope`]: https://doc.rust-lang.org/stable/std/thread/fn.scope.html
71+
[`std::thread::spawn`]: https://doc.rust-lang.org/stable/std/thread/fn.spawn.html
72+
[`Arc`]: https://doc.rust-lang.org/stable/std/sync/struct.Arc.html
73+
74+
3175
### Rust ownership for raw file descriptors/handles (I/O Safety)
3276

3377
Previously, Rust code working with platform APIs taking raw file descriptors (on
@@ -69,7 +113,7 @@ which code they can write.
69113

70114
You can read more about non-lexical lifetimes in [this section of the 2018 edition announcement][nll].
71115

72-
[this blog post]: https://github.com/rust-lang/blog.rust-lang.org/pull/989
116+
[this blog post]: https://blog.rust-lang.org/2022/08/05/nll-by-default.html
73117
[nll]: https://blog.rust-lang.org/2018/12/06/Rust-1.31-and-rust-2018.html#non-lexical-lifetimes
74118

75119
### Stabilized APIs

0 commit comments

Comments
 (0)