首页 > 其他分享 >无涯教程-Rust - 并发(Concurrency)

无涯教程-Rust - 并发(Concurrency)

时间:2024-01-25 22:32:36浏览次数:24  
标签:thread 无涯 number hi 线程 Concurrency main spawned 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 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()方法,主线程等待生成的线程完成。

参考链接

https://www.learnfk.com/rust/rust-concurrency.html

标签:thread,无涯,number,hi,线程,Concurrency,main,spawned,Rust
From: https://blog.51cto.com/u_14033984/9420966

相关文章

  • 无涯教程-Rust - 智能指针
    Rust默认情况下在堆栈上分配所有内容,您可以通过将它们包装在智能指针(如Box)中来将它们存储在堆上,智能指针实现下表中列出的特征-Sr.NoTraitnamePackage&描述1Derefstd::ops::Deref用于不可变的取消引用操作,如*v。2Dropstd::ops::Drop当值超出范围时用于......
  • 无涯教程-Rust - 迭代&闭包
    在本章中,我们将学习RUST中的迭代器和闭包如何工作。Iterator迭代器迭代器有助于迭代值的集合,例如数组,向量,Map映射等,迭代器实现Rust标准库中定义的Iteratortrait,iter()方法返回集合的迭代器对象,迭代器对象中的值称为元素,迭代器的next()方法可用于遍历元素,当到达集合末尾时,next......
  • 无涯教程-Rust - 文件输入&输出
    除了对控制台进行读写之外,Rust还允许对文件进行读写,File结构代表一个文件,它允许程序对文件执行读写操作,File结构中的所有方法均返回io::Result枚举的变体。写入文件以下程序创建文件"data.txt",create()方法用于创建文件,如果文件创建成功,该方法将返回文件句柄,最后一行write_a......
  • 无涯教程-Rust - 输入&输出
    本章讨论如何接受来自标准输入Input的值以及如何将值显示到标准输出Output,在本章中,我们还将讨论传递命令行参数。读和写Rust的input和output标准库函数围绕两个特征进行组织-Read读Write写Sr.NoTrait&描述Example1Read- 实现Read的类型具有面向字节输入的方法。S......
  • 25从零开始用Rust编写nginx,序列化之serde是如何工作的
    wmproxywmproxy已用Rust实现http/https代理,socks5代理,反向代理,静态文件服务器,四层TCP/UDP转发,内网穿透,后续将实现websocket代理等,会将实现过程分享出来,感兴趣的可以一起造个轮子项目地址国内:https://gitee.com/tickbh/wmproxygithub:https://github.com/tickbh/wmproxy序......
  • 无涯教程-Rust - 错误处理
    在Rust中,错误可以分为两大类,如下表所示。Name&描述UsageRecoverable可恢复的错误ResultenumUnRecoverable无法恢复的错误panicmacro与其他编程语言不同,Rust没有Exception异常,它返回可恢复错误的枚举Result<T,E>,如果程序遇到不可恢复的错误,则调用panic宏。Panic......
  • Rust 一个 I/O 项目:构建一个命令行程序
    本篇在原文基础上有删减和添加,增加了一些细节内容,原文请参考一个I/O项目:构建一个命令行程序。目录接受命令行参数读取参数值将参数值保存进变量读取文件重构改进模块性和错误处理二进制项目的关注分离提取参数解析器组合配置值使用clone的权衡取舍创建一个Config的构造函数......
  • rust使用lazy_static对全局变量多线程并发读写示例
    首先需要在项目依赖Cargo.toml添加lazy_static依赖项[dependencies]lazy_static="1.4.0"示例代码如下:uselazy_static::lazy_static;usestd::sync::{RwLock,RwLockReadGuard,RwLockWriteGuard};usestd::thread;#[derive(Debug)]structSharedData{data:Vec<......
  • 无涯教程-Rust - 元组(Tuple)
    元组是复合数据类型,标量类型只能存储一种类型的数据,如一个i32变量只能存储一个整数值。在复合类型中,我们可以存储多个值,并且可以是不同类型。元组的长度是固定的,一旦声明,它们就无法增长或缩小,元组索引从0开始。Tuple-语法//语法1lettuple_name:(data_type1,data_type2,d......
  • 无涯教程-Rust - 变量声明
    变量是程序可以操纵的命名存储,Rust中的变量与特定的数据类型相关联。数据类型决定变量的内存大小,可以存储在该内存中的值的范围以及可以对该变量执行的一组操作。命名规则在本节中,我们将学习命名变量的不同规则。变量的名称可以由字母,数字和下划线字符组成。必须以字母或下划......