Rust并发


在并发编程中,程序的不同部分独立执行。在并行编程中,程序的不同部分同时执行。随着越来越多的计算机利用其多个处理器,这两个模型同样重要。

线程


我们可以使用线程来同时运行代码。在当前的操作系统中,已执行程序的代码在一个进程中运行,并且操作系统一次管理多个进程。在你的程序中,你还可以具有可以同时运行的独立部分,运行这些独立部分的函数称为线程。

创建一个线程

thread::spawn函数用于创建新线程,生成函数将闭包作为参数,闭包定义需要线程执行的代码。下面的示例在主线程中打印一些文本,在新线程中打印其他文本。

//导入必要的模块
use std::thread;
use std::time::Duration;

fn main() {
    //创建一个新线程
    thread::spawn(|| {
        for i in 1..10 {
            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));
    }
}
hi number 1 from the main thread!
hi number 1 from the spawned thread!
hi number 2 from the main thread!
hi number 2 from the spawned thread!
hi number 3 from the main thread!
hi number 3 from the spawned thread!
hi number 4 from the spawned thread!
hi number 4 from the main thread!

主线程打印从1到4的值。

注意:主线程结束时,新线程将停止。每次该程序的输出可能会有所不同。

thread::sleep函数强制线程在短时间内停止执行,从而允许其他线程运行。线程可能会轮流使用,但这不能保证–这取决于操作系统如何调度线程。在此运行中,即使从代码生成的线程中首先出现了打印语句,也首先打印了主线程。而且,即使将生成的线程编程为将值打印到9,也只能在关闭主线程之前将值打印到5。

Join句柄


产生的线程可能无法运行或完全运行,这是因为主线程快速完成spawn函数。

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

fn main() {
    let handle = thread::spawn(|| {
        for i in 1..10 {
            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();
}
hi number 1 from the main thread!
hi number 1 from the spawned thread!
hi number 2 from the spawned thread!
hi number 2 from the main thread!
hi number 3 from the spawned thread!
hi number 3 from the main thread!
hi number 4 from the main thread!
hi number 4 from the spawned thread!
hi number 5 from the spawned thread!
hi number 6 from the spawned thread!
hi number 7 from the spawned thread!
hi number 8 from the spawned thread!
hi number 9 from the spawned thread!

主线程和衍生线程继续切换。

注意:主线程等待生成的线程完成,因为调用了join()方法。