@@ -56,68 +56,35 @@ place!
56
56
57
57
## Threads
58
58
59
- Rust's standard library provides a library for ' threads' , which allow you to
59
+ Rust's standard library provides a library for threads, which allow you to
60
60
run Rust code in parallel. Here's a basic example of using ` std::thread ` :
61
61
62
62
```
63
63
use std::thread;
64
64
65
65
fn main() {
66
- thread::scoped (|| {
66
+ thread::spawn (|| {
67
67
println!("Hello from a thread!");
68
68
});
69
69
}
70
70
```
71
71
72
- The ` thread::scoped() ` method accepts a closure, which is executed in a new
73
- thread. It's called ` scoped ` because this thread returns a join guard:
72
+ The ` thread::spawn() ` method accepts a closure, which is executed in a
73
+ new thread. It returns a handle to the thread, that can be used to
74
+ wait for the child thread to finish and extract its result:
74
75
75
76
```
76
77
use std::thread;
77
78
78
79
fn main() {
79
- let guard = thread::scoped (|| {
80
- println!( "Hello from a thread!");
80
+ let handle = thread::spawn (|| {
81
+ "Hello from a thread!"
81
82
});
82
83
83
- // guard goes out of scope here
84
+ println!("{}", handle.join().unwrap());
84
85
}
85
86
```
86
87
87
- When ` guard ` goes out of scope, it will block execution until the thread is
88
- finished. If we didn't want this behaviour, we could use ` thread::spawn() ` :
89
-
90
- ```
91
- use std::thread;
92
-
93
- fn main() {
94
- thread::spawn(|| {
95
- println!("Hello from a thread!");
96
- });
97
-
98
- thread::sleep_ms(50);
99
- }
100
- ```
101
-
102
- We need to ` sleep ` here because when ` main() ` ends, it kills all of the
103
- running threads.
104
-
105
- [ ` scoped ` ] ( std/thread/struct.Builder.html#method.scoped ) has an interesting
106
- type signature:
107
-
108
- ``` text
109
- fn scoped<'a, T, F>(self, f: F) -> JoinGuard<'a, T>
110
- where T: Send + 'a,
111
- F: FnOnce() -> T,
112
- F: Send + 'a
113
- ```
114
-
115
- Specifically, ` F ` , the closure that we pass to execute in the new thread. It
116
- has two restrictions: It must be a ` FnOnce ` from ` () ` to ` T ` . Using ` FnOnce `
117
- allows the closure to take ownership of any data it mentions from the parent
118
- thread. The other restriction is that ` F ` must be ` Send ` . We aren't allowed to
119
- transfer this ownership unless the type thinks that's okay.
120
-
121
88
Many languages have the ability to execute threads, but it's wildly unsafe.
122
89
There are entire books about how to prevent errors that occur from shared
123
90
mutable state. Rust helps out with its type system here as well, by preventing
0 commit comments