Skip to content

Latest commit

 

History

History
33 lines (25 loc) · 877 Bytes

demo.md

File metadata and controls

33 lines (25 loc) · 877 Bytes

一个创建新线程的例子

use std::thread;
use std::time::Duration;

fn main() {
    let v = vec![1, 2, 3];

    let handle = thread::spawn(move || {
        println!("Here's a vector: {:?}", v);
        
        for i in 1..100 {
            println!("hi number {} from the spawned thread!", i);
            thread::sleep(Duration::from_millis(1));
        }
    });

    for i in 1..5 {
        println!("hi number {} from the main thread!", i);
        thread::sleep(Duration::from_millis(1));
    }
    handle.join().unwrap();
    println!("main thread exit!");
}

其中

  • move 将会把 v 移动进闭包的环境中(如此将不能在主线程中对其调用 drop 了)
  • thread::spawn 的返回值类型是 JoinHandle。JoinHandle 是一个拥有所有权的值,当对其调用 join 方法时,它会等待其线程结束。

为闭包增加