Rust - 并发(Concurrency)

Rust - 并发(Concurrency) 首页 / Rust入门教程 / Rust - 并发(Concurrency)

在并发编程中,程序的不同部分独立执行,另一方面,在并行编程中,程序的不同部分会同时执行。

线程数

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

创建线程

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 Handles

产生的线程可能无法运行或完全运行,这是因为主线程快速完成,函数spawn <F,T>(f:F)-> JoinHandlelt; T>返回JoinHandle。JoinHandle上的join()方法等待关联的线程完成。

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()方法,主线程等待生成的线程完成。

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

iOS开发高手课 -〔戴铭〕

OpenResty从入门到实战 -〔温铭〕

Flutter核心技术与实战 -〔陈航〕

Node.js开发实战 -〔杨浩〕

互联网人的英语私教课 -〔陈亦峰〕

Spark性能调优实战 -〔吴磊〕

说透低代码 -〔陈旭〕

商业思维案例笔记 -〔曹雄峰〕

PPT设计进阶 · 从基础操作到高级创意 -〔李金宝(Bobbie)〕

好记忆不如烂笔头。留下您的足迹吧 :)