Rust 多线程编程

一个进程一定有一个主线程,主线程之外创建出来的线程称为子线程
多线程编程,其实就是在主线程之外创建子线程,让子线程和主线程并发运行,完成各自的任务。
Rust语言支持多线程编程。

Rust语言标准库中的 std::thread 模块用于多线程编程。
std::thread 提供很很多方法用于创建线程、管理线程和结束线程。

一、创建线程

使用std::thread::spawn()方法创建一个线程。

pub fn spawn<F, T>(f: F) -> JoinHandle<T>

参数 f 是一个闭包,是线程要执行的代码。

范例

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!

咦,执行结果好像出错了? 是吗?
当主线程执行结束,那么就会自动关闭创建出来的子线程。
上面的代码,我们调用 thread::sleep() 函数强制线程休眠一段时间,这就允许不同的线程交替执行。
虽然某个线程休眠时会自动让出cpu,但并不保证其它线程会执行。这取决于操作系统如何调度线程。
这个范例的输出结果是随机的,主线程一旦执行完成程序就会自动退出,不会继续等待子线程。这就是子线程的输出结果不全的原因。

二、让主线程等待子线程

默认情况下,主线程并不会等待子线程执行完毕。为了避免这种情况,我们可以让主线程等待子线程执行完毕然后再继续执行。

Rust标准库提供了 join() 方法用于把子线程加入主线程等待队列。

spawn<F, T>(f: F) -> JoinHandle<T>

范例

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() 方法。

三、move强制所有权迁移

这是一个经常遇到的情况:
实例

use std::thread;
fn main() {let s = "hello";let handle = thread::spawn(|| {println!("{}", s);});handle.join().unwrap();
}

在子线程中尝试使用当前函数的资源,这一定是错误的!因为所有权机制禁止这种危险情况的产生,它将破坏所有权机制销毁资源的一定性。我们可以使用闭包的move关键字来处理:
实例

use std::thread;
fn main() {let s = "hello";let handle = thread::spawn(move || {println!("{}", s);});handle.join().unwrap();
}

四、消息传递

使用通道传递消息,通道有两部分组成,一个发送者(transmitter)和一个接收者(receiver)。
std::sync::mpsc包含了消息传递的方法:
实例

use std::thread;
use std::sync::mpsc;
fn main() {let (tx, rx) = mpsc::channel();thread::spawn(move || {let val = String::from("hi");tx.send(val).unwrap();});let received = rx.recv().unwrap();println!("Got: {}", received);
}
运行结果:
Got: hi

子线程获得了主线程的发送者tx,并调用了它的send方法发送了一个字符串,然后主线程就通过对应的接收者rx接收到了。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/92430.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

flutter播放rtmp视频

安装 dependencies:fijkplayer: ^0.11.0使用方法 import package:fijkplayer/fijkplayer.dart; import package:flutter/material.dart;class RtmpPlayerPage extends StatefulWidget {const RtmpPlayerPage({super.key});overrideState<RtmpPlayerPage> createState()…

【Python】返回指定时间对应的时间戳

使用模块datetime&#xff0c;附赠一个没啥用的“时间推算”功能(获取n天后对应的时间 代码&#xff1a; import datetimedef GetTimestamp(year,month,day,hour,minute,second,*,relativeNone,timezoneNone):#返回指定时间戳。指定relative时进行时间推算"""根…

TFT LCD刷新原理及LCD时序参数总结(LCD时序,写的挺好)

cd工作原理目前不了解&#xff0c;日后会在博客中添加这一部分的内容。 1.LCD工作原理[1] 我对LCD的工作原理也仅仅处在了解的地步&#xff0c;下面基于NXP公司对LCD工作原理介绍的ppt来学习一下。 LCD(liquid crystal display,液晶显示屏) 是由液晶段阵列组成&#xff0c;当…

目标检测YOLO实战应用案例100讲-机器人路径规划与目标检测

目录 前言 路径规划研究现状 全局路径规划方法 局部路径规划方法

【网络协议】ARP协议

为什么网络需要同时借助MAC地址这种物理地址和IP地址这种逻辑地址进行通信&#xff1f; 尽管目前MAC地址可以通过逻辑的方式进行修改&#xff0c;但它最初是被设计为不可人为更改的硬件地址。虽然MAC地址也可以满足唯一性的要求&#xff0c;但由于它不可由管理员根据需求通过逻…

newstarctf

wp web: 1.rce 可以发现这个变量名有下划线也有点。 $code$_POST[e_v.a.l]; 这时候如果直接按这个变量名来传参&#xff0c;php 是无法接收到这个值的&#xff0c;具体原因是 php 会自动把一些不合法的字符转化为下划线&#xff08;注&#xff1a;php8以下&#xff09;&am…

springboot和vue:八、vue快速入门

vue快速入门 新建一个html文件 导入 vue.js 的 script 脚本文件 <script src"https://unpkg.com/vuenext"></script>在页面中声明一个将要被 vue 所控制的 DOM 区域&#xff0c;既MVVM中的View <div id"app">{{ message }} </div…

Node.js 是如何处理请求的

前言&#xff1a;在服务器软件中&#xff0c;如何处理请求是非常核心的问题。不管是底层架构的设计、IO 模型的选择&#xff0c;还是上层的处理都会影响一个服务器的性能&#xff0c;本文介绍 Node.js 在这方面的内容。 TCP 协议的核心概念 要了解服务器的工作原理首先需要了…

C++17中std::filesystem::directory_entry的使用

C17引入了std::filesystem库(文件系统库, filesystem library)。这里整理下std::filesystem::directory_entry的使用。 std::filesystem::directory_entry&#xff0c;目录项&#xff0c;获取文件属性。此directory_entry类主要用法包括&#xff1a; (1).构造函数、…

EasyExcel的源码流程(导入Excel)

1. 入口 2. EasyExcel类继承了EasyExcelFactory类&#xff0c;EasyExcel自动拥有EasyExcelFactory父类的所有方法&#xff0c;如read()&#xff0c;readSheet()&#xff0c;write()&#xff0c;writerSheet()等等。 3. 进入.read()方法&#xff0c;需要传入三个参数(文件路径…

【C++】:类和对象(1)

朋友们、伙计们&#xff0c;我们又见面了&#xff0c;本期来给大家解读一下有关C中类和对象的知识点&#xff0c;如果看完之后对你有一定的启发&#xff0c;那么请留下你的三连&#xff0c;祝大家心想事成&#xff01; C 语 言 专 栏&#xff1a;C语言&#xff1a;从入门到精通…

什么是序列化和反序列化?

什么是序列化和反序列化&#xff1f; 什么是序列化和反序列化&#xff1f; 序列化和反序列化是计算机科学中两个重要的概念&#xff0c;主要应用在数据存储和网络传输等场景。序列化是将数据结构或对象状态转换为可以存储或传输的形式的过程。这种形式要求在重新构建原始对象…

Windows电脑显示部分功能被组织控制

目录 问题描述 解决方法 总结 问题描述 如果你的电脑出现以上情况&#xff0c;建议你使用我这种方法&#xff08;万不得已&#xff09; 解决方法 原因就是因为当时你的电脑在激活的时候是选择了组织性激活的&#xff0c;所以才会不管怎么搞&#xff0c;都无法摆脱组织的控…

十五、异常(4)

本章概要 Java 标志异常 特例&#xff1a;RuntimeException 使用 finally 进行清理 finally 用来做什么&#xff1f;在 return 中使用 finally缺憾&#xff1a;异常丢失 Java 标准异常 Throwable 这个 Java 类被用来表示任何可以作为异常被抛出的类。Throwable 对象可分为两…

C/C++笔试面试真题

C/C++笔试面试真题 1、堆和栈的区别 1、栈由系统自动分配,而堆是人为申请开辟; 2、栈获得的空间较小,而堆获得的空间较大; 3、栈由系统自动分配,速度较快,而堆一般速度比较慢; 4、栈是连续的空间,而堆是不连续的空间。 2、什么是野指针?产生的的原因? 野指针的指向的…

ubuntu下源码编译方式安装opencv

基础条件 ubuntu 20.04 opencv 3.4.3 opencv 源码编译的安装步骤 第一步&#xff0c; 首先clone源码 git clone https://github.com/opencv/opencv.git第二步&#xff0c;依赖包&#xff0c;执行下面的命令 sudo apt-get install build-essential sudo apt-get install cmak…

记一次Mybatis驼峰命名导致的线上BUG及处理方案

前言 方向从一开始就错了&#xff0c;还是执着的去寻找问题的解决方案&#xff0c;简直就是一场重大灾难&#xff0c;但这也是每个修行者的必由之路。这个线上问题&#xff0c;差点让我的心里防线崩溃&#xff0c;苦寻无门&#xff0c;最终得以解决也多亏了身边的各路大佬的群…

Android studio “Layout Inspector“工具在Android14 userdebug设备无法正常使用

背景描述 做rom开发的都知道&#xff0c;“Layout Inspector”和“Attach Debugger to Android Process”是studio里很好用的工具&#xff0c;可以用来查看布局、调试系统进程&#xff08;比如setting、launcher、systemui&#xff09;。 问题描述 最进刚开始一个Android 14…

数据结构与算法之堆: Leetcode 215. 数组中的第K个最大元素 (Typescript版)

数组中的第K个最大元素 https://leetcode.cn/problems/kth-largest-element-in-an-array/ 描述 给定整数数组 nums 和整数 k&#xff0c;请返回数组中第 k 个最大的元素。请注意&#xff0c;你需要找的是数组排序后的第 k 个最大的元素&#xff0c;而不是第 k 个不同的元素。…

Android Shape设置背景

设置背景时&#xff0c;经常这样 android:background“drawable/xxx” 。如果是纯色图片&#xff0c;可以考虑用 shape 替代。 shape 相比图片&#xff0c;减少资源占用&#xff0c;缩减APK体积。 开始使用。 <?xml version"1.0" encoding"utf-8"?…