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
}
相关文章:
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::Du…...
合并两个有序链表(冒泡排序实现)
实例要求:将两个升序链表合并为一个新的 升序 链表并返回;新链表是通过拼接给定的两个链表的所有节点组成的;实例分析:先拼接两个链表,在使用冒泡排序即可;示例代码: struct ListNode* mergeTwo…...
【iOS】——知乎日报第五周总结
文章目录 一、评论区展开与收缩二、FMDB库实现本地持久化FMDB常用类:FMDB的简单使用: 三、点赞和收藏的持久化 一、评论区展开与收缩 有的评论没有被回复评论或者被回复评论过短,这时就不需要展开全文的按钮,所以首先计算被回复评…...
gRPC 四模式之 双向流RPC模式
双向流RPC模式 在双向流 RPC 模式中,客户端以消息流的形式发送请求到服务器端,服务器端也以消息流的形式进行响应。调用必须由客户端发起,但在此之后,通信完全基于 gRPC 客户端和服务器端的应用程序逻辑。 为什么有了双向流模式…...
五分钟,Docker安装kafka 3.5,kafka-map图形化管理工具
首先确保已经安装docker,如果是windows安装docker,可参考 wsl2安装docker 1、安装zk docker run -d --restartalways -e ALLOW_ANONYMOUS_LOGINyes --log-driver json-file --log-opt max-size100m --log-opt max-file2 --name zookeeper -p 2181:218…...
2023.11.18html中如何使用input/button进行网页跳转
2023.11.18html中如何使用input/button进行网页跳转 在做网页时有时会用元素,有时会用元素进行form表单操作或者网页跳转,但是用bootstrap时两种元素会出现不同的样式,为了样式一致,有时需要使用这两种元素相互实现其常用功能。 …...
java文件压缩加密,使用流的方式
使用net.lingala.zip4j来进行文件加密压缩。 添加依赖net.lingala.zip4j包依赖,这里使用的是最新的包2.11.5版本。 <dependency><groupId>net.lingala.zip4j</groupId><artifactId>zip4j</artifactId><version>${zip4j.versi…...
月子会所信息展示服务预约小程序的作用是什么
传统线下门店经营只依赖自然流量咨询或简单的线上付费推广是比较低效的,属于靠“天”吃饭,如今的年轻人学历水平相对较高,接触的事物或接受的思想也更多更广,加之生活水平提升及互联网带来的长期知识赋能,因此在寻找/咨…...
Windows核心编程 静态库与动态库
资源文件 .rc 文件 会被 rc.exe 变成 .res 文件(二进制文件) 在链接时链接进入 .exe 文件 一、如何保护源码 程序编译链接过程 不想让别人拿到源代码,但是想让其使用功能,根据上图观察,把自己生成的obj给对方,对方拿到obj后&…...
【Spring Boot】如何自定义序列化以及反序列器
在我们使用默认的消息转换器,将java的Long类型通过json数据传输到前端JS时,会导致Long类型的精度丢失,这是因为JS处理Long类型数字只能精确到前16位,所以我们可以采用自定义序列化方式将Long类型数据统一转为String字符串…...
6 Redis的慢查询配置原理
1、redis的命令执行流程 redis的慢查询只针对步骤3 默认情况下,慢查询的阈值是10ms...
JAVA小游戏 “拼图”
第一步是创建项目 项目名自拟 第二部创建个包名 来规范class 然后是创建类 创建一个代码类 和一个运行类 代码如下: package heima; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import …...
Spring 配置
配置文件最主要的目的 : 解决硬编码的问题(代码写死) SpringBoot 的配置文件,有三种格式 1.properties 2.yaml 3.yml(是 yaml 的简写) SpringBoot 只支持三个文件 1.application.properties 2.application.yaml 3.application.yml yaml 和 yml 是一样的,学会一个就行…...
全新酷盒9.0源码:多功能工具箱软件的最新iapp解决方案
全能工具箱软件酷盒:源码提供iapp解决方案,自定义打造个性化体验 酷盒是一款功能丰富的工具箱软件,内置众多实用功能,并实时更新热门功能。该软件还拥有丰富的资源库,用户可以在线畅玩游戏、免费下载音乐等。 我们提…...
aspose.cells java合并多个excel
背景 有需求需要把多个excel合并到一个excel文件里面,之前一直都是用python来处理办公自动化的东西,但是这个需求用python的openxyl库处理基本只能合并数据,样式没办法一比一合并过去,找了很多解决方案都没法实现,所以…...
【每日一题】三个无重叠子数组的最大和
文章目录 Tag题目来源题目解读解题思路方法一:滑动窗口 写在最后 Tag 【滑动窗口】【数组】【2023-11-19】 题目来源 689. 三个无重叠子数组的最大和 题目解读 解题思路 方法一:滑动窗口 单个子数组的最大和 我们先来考虑一个长度为 k 的子数组的最…...
react之基于@reduxjs/toolkit使用react-redux
react之基于reduxjs/toolkit使用react-redux 一、配置基础环境二、使用React Toolkit 创建 counterStore三、为React注入store四、React组件使用store中的数据五、实现效果六、提交action传递参数七、异步状态操作 一、配置基础环境 1.使用cra快速创建一个react项目 npx crea…...
基于51单片机水位监测控制报警仿真设计( proteus仿真+程序+设计报告+讲解视频)
这里写目录标题 💥1. 主要功能:💥2. 讲解视频:💥3. 仿真💥4. 程序代码💥5. 设计报告💥6. 设计资料内容清单&&下载链接💥[资料下载链接:](https://doc…...
git基本用法和操作
文章目录 创建版本库方式:Git常用操作命令:远程仓库相关命令分支(branch)操作相关命令版本(tag)操作相关命令子模块(submodule)相关操作命令忽略一些文件、文件夹不提交其他常用命令 创建版本库方式: 创建文件夹 在目录下 右键 Git Bush H…...
设计模式-组合模式-笔记
“数据结构”模式 常常有一些组件在内部具有特定的数据结构,如果让客户程序依赖这些特定数据结构,将极大地破坏组件的复用。这时候,将这些特定数据结构封装在内部,在外部提供统一的接口,来实现与特定数据结构无关的访…...
[特殊字符] 智能合约中的数据是如何在区块链中保持一致的?
🧠 智能合约中的数据是如何在区块链中保持一致的? 为什么所有区块链节点都能得出相同结果?合约调用这么复杂,状态真能保持一致吗?本篇带你从底层视角理解“状态一致性”的真相。 一、智能合约的数据存储在哪里…...
使用VSCode开发Django指南
使用VSCode开发Django指南 一、概述 Django 是一个高级 Python 框架,专为快速、安全和可扩展的 Web 开发而设计。Django 包含对 URL 路由、页面模板和数据处理的丰富支持。 本文将创建一个简单的 Django 应用,其中包含三个使用通用基本模板的页面。在此…...
Linux相关概念和易错知识点(42)(TCP的连接管理、可靠性、面临复杂网络的处理)
目录 1.TCP的连接管理机制(1)三次握手①握手过程②对握手过程的理解 (2)四次挥手(3)握手和挥手的触发(4)状态切换①挥手过程中状态的切换②握手过程中状态的切换 2.TCP的可靠性&…...
工程地质软件市场:发展现状、趋势与策略建议
一、引言 在工程建设领域,准确把握地质条件是确保项目顺利推进和安全运营的关键。工程地质软件作为处理、分析、模拟和展示工程地质数据的重要工具,正发挥着日益重要的作用。它凭借强大的数据处理能力、三维建模功能、空间分析工具和可视化展示手段&…...
Spring Boot面试题精选汇总
🤟致敬读者 🟩感谢阅读🟦笑口常开🟪生日快乐⬛早点睡觉 📘博主相关 🟧博主信息🟨博客首页🟫专栏推荐🟥活动信息 文章目录 Spring Boot面试题精选汇总⚙️ **一、核心概…...
【C语言练习】080. 使用C语言实现简单的数据库操作
080. 使用C语言实现简单的数据库操作 080. 使用C语言实现简单的数据库操作使用原生APIODBC接口第三方库ORM框架文件模拟1. 安装SQLite2. 示例代码:使用SQLite创建数据库、表和插入数据3. 编译和运行4. 示例运行输出:5. 注意事项6. 总结080. 使用C语言实现简单的数据库操作 在…...
Xen Server服务器释放磁盘空间
disk.sh #!/bin/bashcd /run/sr-mount/e54f0646-ae11-0457-b64f-eba4673b824c # 全部虚拟机物理磁盘文件存储 a$(ls -l | awk {print $NF} | cut -d. -f1) # 使用中的虚拟机物理磁盘文件 b$(xe vm-disk-list --multiple | grep uuid | awk {print $NF})printf "%s\n"…...
【Go语言基础【12】】指针:声明、取地址、解引用
文章目录 零、概述:指针 vs. 引用(类比其他语言)一、指针基础概念二、指针声明与初始化三、指针操作符1. &:取地址(拿到内存地址)2. *:解引用(拿到值) 四、空指针&am…...
Vue ③-生命周期 || 脚手架
生命周期 思考:什么时候可以发送初始化渲染请求?(越早越好) 什么时候可以开始操作dom?(至少dom得渲染出来) Vue生命周期: 一个Vue实例从 创建 到 销毁 的整个过程。 生命周期四个…...
git: early EOF
macOS报错: Initialized empty Git repository in /usr/local/Homebrew/Library/Taps/homebrew/homebrew-core/.git/ remote: Enumerating objects: 2691797, done. remote: Counting objects: 100% (1760/1760), done. remote: Compressing objects: 100% (636/636…...
