]>
Commit | Line | Data |
---|---|---|
2c00a5a8 XL |
1 | # Threads |
2 | ||
3 | Rust provides a mechanism for spawning native OS threads via the `spawn` | |
4 | function, the argument of this function is a moving closure. | |
5 | ||
6 | ```rust,editable | |
7 | use std::thread; | |
8 | ||
1b1a35ee | 9 | const NTHREADS: u32 = 10; |
2c00a5a8 XL |
10 | |
11 | // This is the `main` thread | |
12 | fn main() { | |
13 | // Make a vector to hold the children which are spawned. | |
14 | let mut children = vec![]; | |
15 | ||
16 | for i in 0..NTHREADS { | |
17 | // Spin up another thread | |
18 | children.push(thread::spawn(move || { | |
19 | println!("this is thread number {}", i); | |
20 | })); | |
21 | } | |
22 | ||
23 | for child in children { | |
24 | // Wait for the thread to finish. Returns a result. | |
25 | let _ = child.join(); | |
26 | } | |
27 | } | |
28 | ``` | |
29 | ||
30 | These threads will be scheduled by the OS. |