mirror of
https://github.com/rust-lang/rust.git
synced 2025-02-04 02:54:00 +00:00
rollup merge of #21020: steveklabnik/gh20844
Thank you @bluss for the suggested implementation. Fixes #20844
This commit is contained in:
commit
6155ce53b6
@ -392,20 +392,21 @@ Here's an example of a concurrent Rust program:
|
|||||||
use std::thread::Thread;
|
use std::thread::Thread;
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
for _ in range(0u, 10u) {
|
let guards: Vec<_> = (0..10).map(|_| {
|
||||||
Thread::spawn(move || {
|
Thread::scoped(|| {
|
||||||
println!("Hello, world!");
|
println!("Hello, world!");
|
||||||
});
|
})
|
||||||
}
|
}).collect();
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
This program creates ten threads, who all print `Hello, world!`. The
|
This program creates ten threads, which all print `Hello, world!`. The `scoped`
|
||||||
`spawn` function takes one argument, a closure, indicated by the
|
function takes one argument, a closure, indicated by the double bars `||`. This
|
||||||
double bars `||`. (The `move` keyword indicates that the closure takes
|
closure is executed in a new thread created by `scoped`. The method is called
|
||||||
ownership of any data it uses; we'll have more on the significance of
|
`scoped` because it returns a 'join guard', which will automatically join the
|
||||||
this shortly.) This closure is executed in a new thread created by
|
child thread when it goes out of scope. Because we `collect` these guards into
|
||||||
`spawn`.
|
a `Vec<T>`, and that vector goes out of scope at the end of our program, our
|
||||||
|
program will wait for every thread to finish before finishing.
|
||||||
|
|
||||||
One common form of problem in concurrent programs is a 'data race.'
|
One common form of problem in concurrent programs is a 'data race.'
|
||||||
This occurs when two different threads attempt to access the same
|
This occurs when two different threads attempt to access the same
|
||||||
|
Loading…
Reference in New Issue
Block a user