初面网初面网

并发

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

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

fn spawn_function() {
  for i in 0..5 {
    println!("spawned thread print {}", i);
    // 等待子线程执行完毕
    thread::sleep(Duration::from_millis(1));
  }
}

fn main() {
  // 关键语句,创建一个新的线程
  thread::spawn(spawn_function);
}

如果需要等待子线程执行完毕,可以使用join方法

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

fn spawn_function() {
  for i in 0..5 {
    println!("spawned thread print {}", i);
    // 等待子线程执行完毕
    thread::sleep(Duration::from_millis(1));
  }
}

fn main() {
  // 关键语句,创建一个新的线程
  let handle = thread::spawn(spawn_function);
  // 等待子线程执行完毕。如果子线程执行出错,unwrap会panic
  handle.join().unwrap();
}

简单的线程变量借用

use std::thread;
use std::sync::Arc;
use std::time::Duration;

struct Info{
  x: i32,
  y: i32,
}

fn spawn_function(data: Arc<i32>) {
  let p1 = Point { x: 25, y: 25 };
  // 一个线程的时候,可以使用move关键字。多线程的时候不行
  let handle = thread::spawn(move || {
    println!("spawned thread print {}, {}", p1.x, p1.y);
  });
}

更新于 2026/3/15