Rust8.2 Fearless Concurrency 无畏并发

Rust学习笔记

Rust编程语言入门教程课程笔记

参考教材: The Rust Programming Language (by Steve Klabnik and Carol Nichols, with contributions from the Rust Community)

Lecture 16: Fearless Concurrency 无畏并发

src/main.rs

use std::thread;
use std::time::Duration;
use std::sync::mpsc;
use std::sync::{Mutex, Arc};fn main() {//Using Threads to Run Code Simultaneously//Creating a New Thread with spawnlet 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));}// output:// 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 main thread!// hi number 4 from the spawned thread!//In this run, the main thread printed first, //even though the print statement from the spawned thread appears first in the code. //And even though we told the spawned thread to print until i is 9, //it only got to 5 before the main thread shut down.//Waiting for All Threads to Finish Using join Handleshandle.join().unwrap();let v = vec![1, 2, 3];let handle = thread::spawn(move || {println!("Here's a vector: {:?}", v);});//move closure: v is moved into the closure// drop(v); // oh no! v is moved into the threadhandle.join().unwrap();//Using Message Passing to Transfer Data Between Threadslet (tx, rx) = mpsc::channel();thread::spawn(move || {let val = String::from("hi");// tx.send(val).unwrap();tx.send(val).unwrap();// println!("val is {}", val); // error: value borrowed here after move});let received = rx.recv().unwrap();//recv blocks the main thread’s execution and waits until a value is sent down the channelprintln!("Got: {}", received);//try_recv: without blocking//Sending Multiple Values and Seeing the Receiver Waitinglet (tx, rx) = mpsc::channel();thread::spawn(move || {let vals = vec![String::from("hello"),String::from("from"),String::from("the"),String::from("thread"),];for val in vals {tx.send(val).unwrap();thread::sleep(Duration::from_secs(1));}});for received in rx {println!("Got: {}", received);}//Shared-State Concurrency//Mutexes: Mutual Exclusion//API: lock, unwrap, Mutex<T> (smart pointer)let m = Mutex::new(5);{let mut num = m.lock().unwrap();*num = 6;// println!("m is {}", m); // error: cannot be formatted with the default formatter}println!("m is {:?}", m);//Sharing a Mutex<T> Between Multiple Threadslet counter = Arc::new(Mutex::new(0));//Arc<T> is an atomically reference counted type//A: atomically, R: reference, C: counted//API in Arc is the same as in Rc let mut handles = vec![];for _ in 0..10 {let counter = Arc::clone(&counter);let handle = thread::spawn(move || {let mut num = counter.lock().unwrap();*num += 1;});handles.push(handle);}for handle in handles {handle.join().unwrap();}println!("Result: {}", *counter.lock().unwrap());//Result: 10//Extensible Concurrency with the Sync and Send Traits//Send: ownership can be transferred between threads//Sync: multiple threads can have references to the same value//Implementing Send and Sync Manually Is Unsafe
}

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

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

相关文章

嵌入式Linux开发面试题和答案

熟练的编程语言&#xff1a; 问&#xff1a;“您在嵌入式系统开发中熟练使用哪些编程语言&#xff1f;”答&#xff1a;在嵌入式系统开发中&#xff0c;我熟练使用C、C和Python等编程语言。C语言因其接近硬件的操作和效率而被广泛应用&#xff1b;C则在需要面向对象编程时提供了…

某手机大厂员工爆料:40岁被裁,每月给88000补贴,连续给12个月,第二年减半,感觉废掉了!...

精彩回顾&#xff1a;进了央企&#xff0c;拿了户口&#xff0c;却感觉被困住了。 人生没有所谓的终点&#xff0c;只有不断再出发的起点&#xff0c;裁员只是人生的一个转角&#xff0c;而非尽头。 在时代的浪潮下&#xff0c;即使身处大厂&#xff0c;依然难逃被裁员的命运。…

【KingbaseES】sys_dump命令详解及示例

概述 sys_dump 是一个将 KingbaseES 数据库保存到一个脚本或者归档文件中的工具&#xff0e;这个脚本文件的格式是纯文本&#xff0c;它包含许多 SQL 命令&#xff0c; 这些 SQL 命令可以用于重建该数据库并将之恢复到保存成脚本的时候的状态&#xff0e;要恢复这些脚本&#…

NX二次开发UF_CAM_ask_lower_limit_plane_usage 函数介绍

文章作者&#xff1a;里海 来源网站&#xff1a;里海NX二次开发3000例专栏 UF_CAM_ask_lower_limit_plane_usage Defined in: uf_cam_planes.h int UF_CAM_ask_lower_limit_plane_usage(tag_t object_tag, UF_PARAM_lwplane_usage_t * usage ) overview 概述 Query the usa…

Shell脚本:Linux Shell脚本学习指南(第二部分Shell编程)一

第二部分&#xff1a;Shell编程&#xff08;一&#xff09; 这一章我们正式进入 Shell 脚本编程&#xff0c;重点讲解变量、字符串、数组、数学计算、选择结构、循环结构和函数。 Shell 的编程思想虽然和 C、Java、Python、C# 等其它编程语言类似&#xff0c;但是在语法细节方…

PaddleDetection训练目标检测模型

PaddleDetection训练目标检测模型 一&#xff0c;安装标注软件二&#xff0c;数据标注和清洗三&#xff0c;安装PaddleDetection环境四&#xff0c;修改配置文件&#xff0c;本文选择的是 PP-PicoDet算法五&#xff0c;训练模型六&#xff0c;训练完成之后导出模型七&#xff0…

php面向对象和面向过程区别

面向过程编程&#xff1a;是一种传统的编码风格&#xff0c;它将代码组织为一系列函数或过程。这些函数可以采用一系列参数和返回值&#xff0c;来完成特定的任务。面向过程编程侧重顺序和功能性。 面向对象编程&#xff1a;是一种编码风格&#xff0c;它将代码组织为对象&…

04_面向对象高级_final与常量

final 1. 基本介绍 final 关键字是最终的意思&#xff0c;可以修饰&#xff08;类、方法、变量&#xff09; 修饰类&#xff1a;该类被称为最终类&#xff0c;特点是不能被继承了修饰方法&#xff1a;该方法被称为最终方法&#xff0c;特点是不能被重写了修饰变量&#xff1…

深入探讨AJAX接口进度监控:实现步骤、代码示例与技术原理

AJAX&#xff08;Asynchronous JavaScript and XML&#xff09;是现代Web开发中常用的异步通信技术。本文将详细分析如何通过AJAX实现接口进度监控&#xff0c;提供实用的代码示例、技术原理解析以及优劣势评估&#xff0c;以帮助开发者更好地应用这一技术。 1. 引言 在复杂的…

Java Swing实现员工工资管理系统(含教程) 可带数据库 Java课程设计

7. 员工工资管理系统 视频教程&#xff1a; 【课程设计】员工工资管理系统-Java Swing-你的课程我设计 功能描述&#xff1a; 系统员工有"工号"、 “姓名”、“性别”、“岗位”、 "入职年份 "、"密码"等属性&#xff1b; 员工使用工号密码登录…

MacOs 删除第三方软件

AppStore下载的软件 如果删除AppStore下载的软件&#xff0c;直接长按软件&#xff0c;点击删除或拖到废纸篓就可以完成软件的删除 第三方软件 但是第三方下载的软件&#xff0c;无法拖进废纸篓&#xff0c;长按软件也没有右上角的小叉 可以通过以下方法实现对软件的卸载 …

2023美亚杯个人赛复盘(三)

案件基本情况&#xff1a; &#xff08;一&#xff09;案情 2023月8月的一天&#xff0c;香港警方在调查一起网络诈骗案件时&#xff0c;发现有三名本地男子&#xff0c;分別为李大輝&#xff08;李大辉&#xff09;&#xff0c;浩賢(浩贤)和Elvis CHUI&#xff0c;并确信这三名…

软件安全检测赋能赣州发展,开源网安与赣州国投完成签约

​11月20日&#xff0c;开源网安与赣州章贡区数智国投科技有限公司签订投资协议&#xff0c;签约后双方将在赣州打造软件供应链安全检测中心&#xff0c;以强大的软件测试能力为数字政府、数字经济等领域提供全面安全检测和软件安全运营监测等服务&#xff0c;提升软件的安全与…

2760. 最长奇偶子数组 --力扣 --JAVA

题目 给你一个下标从 0 开始的整数数组 nums 和一个整数 threshold 。 请你从 nums 的子数组中找出以下标 l 开头、下标 r 结尾 (0 < l < r < nums.length) 且满足以下条件的 最长子数组 &#xff1a; nums[l] % 2 0 对于范围 [l, r - 1] 内的所有下标 i &#xff0c…

电商数据|电商API接口|电商数据分析都会用到的接口不用再找了

导读&#xff1a;上半年&#xff0c;网络零售行业发展迅速&#xff0c;货架电商、直播电商、生鲜电商等领域动作频频。京东“百亿补贴”上线&#xff0c;张勇宣布启动“16N”组织变革&#xff0c;盒马启动上市计划&#xff0c;拼多多APP新增直播入口&#xff0c;快手升级货架场…

JavaScript拖放操作的实现

在页面中设置2个框&#xff1a;一个是被拖放的框&#xff0c;一个是拖放的目的地框。在拖动的时候&#xff0c;只有当鼠标位于拖放的目的地框上方的时候&#xff0c;放开鼠标的时候&#xff0c;被拖放的框&#xff0c;才被移动到鼠标所在的位置&#xff1b;而在其他地方放开鼠标…

SVG 多边形 <polygon>,矩形<rect>的示例代码

本专栏是汇集了一些HTML常常被遗忘的知识&#xff0c;这里算是温故而知新&#xff0c;往往这些零碎的知识点&#xff0c;在你开发中能起到炸惊效果。我们每个人都没有过目不忘&#xff0c;过久不忘的本事&#xff0c;就让这一点点知识慢慢渗透你的脑海。 本专栏的风格是力求简洁…

WPS或Excel查找A列中有B列没有的值

就这一行代码&#xff1a; 在C列输入&#xff1a; IF(COUNTIF(B:B,A1)>0,"该行A列中值B列有","该行A列中值B列没有")

企业微信将应用安装到工作台

在上篇中介绍了配置小程序应用及指令、数据回调获取第三方凭证&#xff1b; 本篇将介绍如何将应用安装到企业工作台。 添加测试企业 通过【应用管理】->【测试企业配置】添加测试企业。 通过企业微信扫描二维码添加测试企业。 注意&#xff1a;需要扫描的账号为管理员权限…

蓝桥杯单片机综合练习——工厂灯光控制

一、题目 二、代码 #include <reg52.h>sfr AUXR 0x8e; //定义辅助寄存器sbit S5 P3^2; //定义S5按键引脚 sbit S4 P3^3; //定义S4按键引脚unsigned char led_stat 0xff; //定义LED当前状态 unsigned char count 0; //定义50ms定时中断累…