当前位置: 首页 > news >正文

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…...

合并两个有序链表(冒泡排序实现)

实例要求&#xff1a;将两个升序链表合并为一个新的 升序 链表并返回&#xff1b;新链表是通过拼接给定的两个链表的所有节点组成的&#xff1b;实例分析&#xff1a;先拼接两个链表&#xff0c;在使用冒泡排序即可&#xff1b;示例代码&#xff1a; struct ListNode* mergeTwo…...

【iOS】——知乎日报第五周总结

文章目录 一、评论区展开与收缩二、FMDB库实现本地持久化FMDB常用类&#xff1a;FMDB的简单使用&#xff1a; 三、点赞和收藏的持久化 一、评论区展开与收缩 有的评论没有被回复评论或者被回复评论过短&#xff0c;这时就不需要展开全文的按钮&#xff0c;所以首先计算被回复评…...

gRPC 四模式之 双向流RPC模式

双向流RPC模式 在双向流 RPC 模式中&#xff0c;客户端以消息流的形式发送请求到服务器端&#xff0c;服务器端也以消息流的形式进行响应。调用必须由客户端发起&#xff0c;但在此之后&#xff0c;通信完全基于 gRPC 客户端和服务器端的应用程序逻辑。 为什么有了双向流模式…...

五分钟,Docker安装kafka 3.5,kafka-map图形化管理工具

首先确保已经安装docker&#xff0c;如果是windows安装docker&#xff0c;可参考 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进行网页跳转 在做网页时有时会用元素&#xff0c;有时会用元素进行form表单操作或者网页跳转&#xff0c;但是用bootstrap时两种元素会出现不同的样式&#xff0c;为了样式一致&#xff0c;有时需要使用这两种元素相互实现其常用功能。 …...

java文件压缩加密,使用流的方式

使用net.lingala.zip4j来进行文件加密压缩。 添加依赖net.lingala.zip4j包依赖&#xff0c;这里使用的是最新的包2.11.5版本。 <dependency><groupId>net.lingala.zip4j</groupId><artifactId>zip4j</artifactId><version>${zip4j.versi…...

月子会所信息展示服务预约小程序的作用是什么

传统线下门店经营只依赖自然流量咨询或简单的线上付费推广是比较低效的&#xff0c;属于靠“天”吃饭&#xff0c;如今的年轻人学历水平相对较高&#xff0c;接触的事物或接受的思想也更多更广&#xff0c;加之生活水平提升及互联网带来的长期知识赋能&#xff0c;因此在寻找/咨…...

Windows核心编程 静态库与动态库

资源文件 .rc 文件 会被 rc.exe 变成 .res 文件(二进制文件) 在链接时链接进入 .exe 文件 一、如何保护源码 程序编译链接过程 不想让别人拿到源代码&#xff0c;但是想让其使用功能&#xff0c;根据上图观察&#xff0c;把自己生成的obj给对方&#xff0c;对方拿到obj后&…...

【Spring Boot】如何自定义序列化以及反序列器

在我们使用默认的消息转换器&#xff0c;将java的Long类型通过json数据传输到前端JS时&#xff0c;会导致Long类型的精度丢失&#xff0c;这是因为JS处理Long类型数字只能精确到前16位&#xff0c;所以我们可以采用自定义序列化方式将Long类型数据统一转为String字符串&#xf…...

6 Redis的慢查询配置原理

1、redis的命令执行流程 redis的慢查询只针对步骤3 默认情况下&#xff0c;慢查询的阈值是10ms...

JAVA小游戏 “拼图”

第一步是创建项目 项目名自拟 第二部创建个包名 来规范class 然后是创建类 创建一个代码类 和一个运行类 代码如下&#xff1a; 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解决方案

全能工具箱软件酷盒&#xff1a;源码提供iapp解决方案&#xff0c;自定义打造个性化体验 酷盒是一款功能丰富的工具箱软件&#xff0c;内置众多实用功能&#xff0c;并实时更新热门功能。该软件还拥有丰富的资源库&#xff0c;用户可以在线畅玩游戏、免费下载音乐等。 我们提…...

aspose.cells java合并多个excel

背景 有需求需要把多个excel合并到一个excel文件里面&#xff0c;之前一直都是用python来处理办公自动化的东西&#xff0c;但是这个需求用python的openxyl库处理基本只能合并数据&#xff0c;样式没办法一比一合并过去&#xff0c;找了很多解决方案都没法实现&#xff0c;所以…...

【每日一题】三个无重叠子数组的最大和

文章目录 Tag题目来源题目解读解题思路方法一&#xff1a;滑动窗口 写在最后 Tag 【滑动窗口】【数组】【2023-11-19】 题目来源 689. 三个无重叠子数组的最大和 题目解读 解题思路 方法一&#xff1a;滑动窗口 单个子数组的最大和 我们先来考虑一个长度为 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仿真+程序+设计报告+讲解视频)

这里写目录标题 &#x1f4a5;1. 主要功能&#xff1a;&#x1f4a5;2. 讲解视频&#xff1a;&#x1f4a5;3. 仿真&#x1f4a5;4. 程序代码&#x1f4a5;5. 设计报告&#x1f4a5;6. 设计资料内容清单&&下载链接&#x1f4a5;[资料下载链接&#xff1a;](https://doc…...

git基本用法和操作

文章目录 创建版本库方式&#xff1a;Git常用操作命令&#xff1a;远程仓库相关命令分支(branch)操作相关命令版本(tag)操作相关命令子模块(submodule)相关操作命令忽略一些文件、文件夹不提交其他常用命令 创建版本库方式&#xff1a; 创建文件夹 在目录下 右键 Git Bush H…...

设计模式-组合模式-笔记

“数据结构”模式 常常有一些组件在内部具有特定的数据结构&#xff0c;如果让客户程序依赖这些特定数据结构&#xff0c;将极大地破坏组件的复用。这时候&#xff0c;将这些特定数据结构封装在内部&#xff0c;在外部提供统一的接口&#xff0c;来实现与特定数据结构无关的访…...

线程与协程

1. 线程与协程 1.1. “函数调用级别”的切换、上下文切换 1. 函数调用级别的切换 “函数调用级别的切换”是指&#xff1a;像函数调用/返回一样轻量地完成任务切换。 举例说明&#xff1a; 当你在程序中写一个函数调用&#xff1a; funcA() 然后 funcA 执行完后返回&…...

基于Uniapp开发HarmonyOS 5.0旅游应用技术实践

一、技术选型背景 1.跨平台优势 Uniapp采用Vue.js框架&#xff0c;支持"一次开发&#xff0c;多端部署"&#xff0c;可同步生成HarmonyOS、iOS、Android等多平台应用。 2.鸿蒙特性融合 HarmonyOS 5.0的分布式能力与原子化服务&#xff0c;为旅游应用带来&#xf…...

Mac软件卸载指南,简单易懂!

刚和Adobe分手&#xff0c;它却总在Library里给你写"回忆录"&#xff1f;卸载的Final Cut Pro像电子幽灵般阴魂不散&#xff1f;总是会有残留文件&#xff0c;别慌&#xff01;这份Mac软件卸载指南&#xff0c;将用最硬核的方式教你"数字分手术"&#xff0…...

CocosCreator 之 JavaScript/TypeScript和Java的相互交互

引擎版本&#xff1a; 3.8.1 语言&#xff1a; JavaScript/TypeScript、C、Java 环境&#xff1a;Window 参考&#xff1a;Java原生反射机制 您好&#xff0c;我是鹤九日&#xff01; 回顾 在上篇文章中&#xff1a;CocosCreator Android项目接入UnityAds 广告SDK。 我们简单讲…...

【分享】推荐一些办公小工具

1、PDF 在线转换 https://smallpdf.com/cn/pdf-tools 推荐理由&#xff1a;大部分的转换软件需要收费&#xff0c;要么功能不齐全&#xff0c;而开会员又用不了几次浪费钱&#xff0c;借用别人的又不安全。 这个网站它不需要登录或下载安装。而且提供的免费功能就能满足日常…...

基于Springboot+Vue的办公管理系统

角色&#xff1a; 管理员、员工 技术&#xff1a; 后端: SpringBoot, Vue2, MySQL, Mybatis-Plus 前端: Vue2, Element-UI, Axios, Echarts, Vue-Router 核心功能&#xff1a; 该办公管理系统是一个综合性的企业内部管理平台&#xff0c;旨在提升企业运营效率和员工管理水…...

从 GreenPlum 到镜舟数据库:杭银消费金融湖仓一体转型实践

作者&#xff1a;吴岐诗&#xff0c;杭银消费金融大数据应用开发工程师 本文整理自杭银消费金融大数据应用开发工程师在StarRocks Summit Asia 2024的分享 引言&#xff1a;融合数据湖与数仓的创新之路 在数字金融时代&#xff0c;数据已成为金融机构的核心竞争力。杭银消费金…...

基于Java+VUE+MariaDB实现(Web)仿小米商城

仿小米商城 环境安装 nodejs maven JDK11 运行 mvn clean install -DskipTestscd adminmvn spring-boot:runcd ../webmvn spring-boot:runcd ../xiaomi-store-admin-vuenpm installnpm run servecd ../xiaomi-store-vuenpm installnpm run serve 注意&#xff1a;运行前…...

前端中slice和splic的区别

1. slice slice 用于从数组中提取一部分元素&#xff0c;返回一个新的数组。 特点&#xff1a; 不修改原数组&#xff1a;slice 不会改变原数组&#xff0c;而是返回一个新的数组。提取数组的部分&#xff1a;slice 会根据指定的开始索引和结束索引提取数组的一部分。不包含…...

Python 训练营打卡 Day 47

注意力热力图可视化 在day 46代码的基础上&#xff0c;对比不同卷积层热力图可视化的结果 import torch import torch.nn as nn import torch.optim as optim from torchvision import datasets, transforms from torch.utils.data import DataLoader import matplotlib.pypl…...