@@ -392,20 +392,21 @@ Here's an example of a concurrent Rust program:
392
392
use std::thread::Thread;
393
393
394
394
fn main() {
395
- for _ in range(0u, 10u) {
396
- Thread::spawn(move || {
395
+ let guards: Vec<_> = (0..10).map(|_| {
396
+ Thread::scoped( || {
397
397
println!("Hello, world!");
398
- });
399
- }
398
+ })
399
+ }).collect();
400
400
}
401
401
```
402
402
403
- This program creates ten threads, who all print `Hello, world!`. The
404
- `spawn` function takes one argument, a closure, indicated by the
405
- double bars `||`. (The `move` keyword indicates that the closure takes
406
- ownership of any data it uses; we' ll have more on the significance of
407
- this shortly.) This closure is executed in a new thread created by
408
- ` spawn` .
403
+ This program creates ten threads, which all print `Hello, world!`. The `scoped`
404
+ function takes one argument, a closure, indicated by the double bars `||`. This
405
+ closure is executed in a new thread created by `scoped`. The method is called
406
+ `scoped` because it returns a ' join guard' , which will automatically join the
407
+ child thread when it goes out of scope. Because we `collect` these guards into
408
+ a `Vec<T>`, and that vector goes out of scope at the end of our program, our
409
+ program will wait for every thread to finish before finishing.
409
410
410
411
One common form of problem in concurrent programs is a ' data race.'
411
412
This occurs when two different threads attempt to access the same
0 commit comments