study_example/concurrency/
thread_create.rs

1use std::thread;
2use std::time::Duration;
3
4/// 运行结果如下
5/// ```txt
6/// main thread number 1
7/// thread::spawn number 1
8/// thread::spawn number 2
9/// main thread number 2
10/// thread::spawn number 3
11/// main thread number 3
12/// thread::spawn number 4
13/// main thread number 4
14/// thread::spawn number 5
15/// ```
16fn create_multi_thread_task() {
17    thread::spawn(|| {
18        for i in 1..10 {
19            println!("thread::spawn number {}", i);
20            thread::sleep(Duration::from_millis(1));
21        }
22    });
23    for i in 1..5 {
24        println!("main thread number {}", i);
25        thread::sleep(Duration::from_millis(1));
26    }
27}
28
29/// 运行结果如下
30/// ```txt
31/// main thread number 1
32/// thread::spawn number 1
33/// main thread number 2
34/// thread::spawn number 2
35/// thread::spawn number 3
36/// main thread number 3
37/// thread::spawn number 4
38/// main thread number 4
39/// thread::spawn number 5
40/// thread::spawn number 6
41/// thread::spawn number 7
42/// thread::spawn number 8
43/// thread::spawn number 9
44/// ```
45fn create_multi_thread_task_all_done() {
46    let handle = thread::spawn(|| {
47        for i in 1..10 {
48            println!("thread::spawn number {}", i);
49            thread::sleep(Duration::from_millis(1));
50        }
51    });
52    for i in 1..5 {
53        println!("main thread number {}", i);
54        thread::sleep(Duration::from_millis(1));
55    }
56    handle.join().unwrap();
57}
58
59fn move_to_clousure_with_thread() {
60    let v = vec![1, 23, 456];
61    // error[E0373]: closure may outlive the current function, but it borrows `v`, which is owned by the current function
62    // Rust 无法判断生成的线程将运行多长时间,因此它不知道对 v 的引用是否始终有效,采用move强制闭包获取使用值的所有权
63    let handle = thread::spawn(move || {
64        println!("vector: {:?}", v);
65    });
66    // error[E0382]: use of moved value: `v`
67    // drop(v);
68    handle.join().unwrap();
69}
70
71pub fn thread_create_study() {
72    create_multi_thread_task();
73    create_multi_thread_task_all_done();
74    move_to_clousure_with_thread();
75}