Rust 并发

发布时间: 更新时间: 总字数:348 阅读时间:1m 作者: 分享 复制网址

本文介绍Rust的并发。

介绍

Rust 并发包括:

  • Concurrent 程序的不同部分之间独立的执行
  • Parallel 程序的不同部分同时运行

进程 vs 线程

进程 Proces 和 线程 thread 区别详见:进程、线程、协程的作用和区别

多线程的问题

  • 方式数据或资源竞争
  • 死锁

示例

使用线程同时运行代码

使用 thread::spawn 函数创建新线程:

  • 参数:一个闭包(在新线程里运行的代码)
  • 返回值类型是 JoinHandle,它持有值的所有权,通过 join 方法等待对应的其它线程的完成,否则主线程结束时,子线程也结束
    • join 方法会阻塞当前线程的执行,直到 handle 所表示的线程终结
use std::{thread, time::Duration};

fn main() {
    let h = thread::spawn(|| {
        for i in 1..10 {
            println!("{} spawned thread!", i);
            thread::sleep(Duration::from_millis(10));
        }
    });

    // 等待线程完成
    // h.join().unwrap();

    for i in 1..5 {
        println!("{} main thread!", i);
        thread::sleep(Duration::from_millis(10));
    }

    h.join().unwrap();
}
  • move 闭包通常和 thread::spawn 函数一起使用,它允许使用其它线程的数据
    • 通过创建线程时,将值的所有权从一个线程转移到另一个线程
use std::thread;

fn main() {
    let l = vec![1, 2, 3];
    let h = thread::spawn(move || {
        println!("l: {:?}", l);
    });

    h.join().unwrap();
}
Home Archives Categories Tags Statistics
本文总阅读量 次 本站总访问量 次 本站总访客数