@@ -56,68 +56,35 @@ place!
5656
5757## Threads
5858
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
6060run Rust code in parallel. Here's a basic example of using ` std::thread ` :
6161
6262```
6363use std::thread;
6464
6565fn main() {
66- thread::scoped (|| {
66+ thread::spawn (|| {
6767 println!("Hello from a thread!");
6868 });
6969}
7070```
7171
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:
7475
7576```
7677use std::thread;
7778
7879fn main() {
79- let guard = thread::scoped (|| {
80- println!( "Hello from a thread!");
80+ let handle = thread::spawn (|| {
81+ "Hello from a thread!"
8182 });
8283
83- // guard goes out of scope here
84+ println!("{}", handle.join().unwrap());
8485}
8586```
8687
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-
12188Many languages have the ability to execute threads, but it's wildly unsafe.
12289There are entire books about how to prevent errors that occur from shared
12390mutable state. Rust helps out with its type system here as well, by preventing
0 commit comments