rust并发
文章目录
- Rust对多线程的支持
- std::thread::spawn创建线程
- 线程与 move 闭包
- 使用消息传递在线程间传送数据
- std::sync::mpsc::channel()
- for received in rx接收
- 两个producer
- 共享状态并发
- std::sync::Mutex
- 在多个线程间共享Mutex,使用std::sync::Arc
- 参考
Rust对多线程的支持
rust默认仅支持一对一线程,也就是说操作系统线程。
可以引入crate包来使用绿色线程。
std::thread::spawn创建线程
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();
}
编译
cargo run
warning: unused `Result` that must be used--> src/main.rs:17:5|
17 | handle.join();| ^^^^^^^^^^^^^|= note: this `Result` may be an `Err` variant, which should be handled= note: `#[warn(unused_must_use)]` on by default
help: use `let _ = ...` to ignore the resulting value|
17 | let _ = handle.join();| +++++++warning: `smartPtr` (bin "smartPtr") generated 1 warningFinished `dev` profile [unoptimized + debuginfo] target(s) in 0.00sRunning `target/debug/smartPtr`
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!
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!
线程与 move 闭包
use std::thread;fn main() {let v = vec![1, 2, 3];let handle = thread::spawn(move || {println!("Here's a vector: {:?}", v);});handle.join().unwrap();
}
编译
cargo runBlocking waiting for file lock on build directoryCompiling smartPtr v0.1.0 (/home/wangji/installer/rust/bobo/smartPtr)Finished `dev` profile [unoptimized + debuginfo] target(s) in 19.07sRunning `target/debug/smartPtr`
Here's a vector: [1, 2, 3]
使用消息传递在线程间传送数据
std::sync::mpsc::channel()
只支持多个生产者和一个消费者
use std::sync::mpsc; //mpsc:multi-producer, single-consumer
use std::thread;fn main() {let (tx, rx) = mpsc::channel();thread::spawn(move || {let val = String::from("hi");tx.send(val).unwrap();});// recv()会阻塞// try_recv()是非阻塞,适合使用loop来尝试接收let received = rx.recv().unwrap();println!("Got: {}", received);
}
for received in rx接收
use std::sync::mpsc;
use std::thread;
use std::time::Duration;fn main() {let (tx, rx) = mpsc::channel();thread::spawn(move || {let vals = vec![String::from("hi"),String::from("from"),String::from("the"),String::from("thread"),];for val in vals {tx.send(val).unwrap();thread::sleep(Duration::from_secs(1));}});// 当发送方tx结束了,接收方rx就会结束(for循环也会结束)for received in rx {println!("Got: {}", received);}
}
两个producer
use std::sync::mpsc;
use std::thread;
use std::time::Duration;fn main() {// --snip--let (tx, rx) = mpsc::channel();let tx1 = tx.clone(); //tx和tx1都连接到mpsc::channel()thread::spawn(move || {let vals = vec![String::from("hi"),String::from("from"),String::from("the"),String::from("thread"),];for val in vals {tx1.send(val).unwrap();thread::sleep(Duration::from_secs(1));}});thread::spawn(move || {let vals = vec![String::from("more"),String::from("messages"),String::from("for"),String::from("you"),];for val in vals {tx.send(val).unwrap();thread::sleep(Duration::from_secs(1));}});for received in rx {println!("Got: {}", received);}// --snip--
}
共享状态并发
std::sync::Mutex
use std::sync::Mutex;fn main() {let m = Mutex::new(5);{// m.lock()会阻塞当前线程,获取锁位置let mut num = m.lock().unwrap();*num = 6;// 退出时会自动释放锁}println!("m = {:?}", m);
}
编译及运行
cargo runCompiling smartPtr v0.1.0 (/home/wangji/installer/rust/bobo/smartPtr)Finished `dev` profile [unoptimized + debuginfo] target(s) in 6.57sRunning `target/debug/smartPtr`
m = Mutex { data: 6, poisoned: false, .. }
在多个线程间共享Mutex,使用std::sync::Arc
use std::sync::Arc;
use std::sync::Mutex;
use std::thread;fn main() {// Mutex于Arc经常一起使用// Rc::new可以让Mutex拥有多个所有者let counter = Arc::new(Mutex::new(0));let mut handles = vec![];for _ in 0..10 {let counter = Arc::clone(&counter); //Rc::clone不是真正的clone,只是增加引用计数let handle = thread::spawn(move || {let mut num = counter.lock().unwrap(); //counter.lock()可以获得可变的引用(类似于RefCell智能指针)*num += 1;});handles.push(handle);}for handle in handles {handle.join().unwrap();}println!("Result: {}", *counter.lock().unwrap());
}
编译
cargo runCompiling smartPtr v0.1.0 (/home/wangji/installer/rust/bobo/smartPtr)Finished `dev` profile [unoptimized + debuginfo] target(s) in 5.85sRunning `target/debug/smartPtr`
Result: 10
参考
- 第16章~创建线程
相关文章:
rust并发
文章目录 Rust对多线程的支持std::thread::spawn创建线程线程与 move 闭包 使用消息传递在线程间传送数据std::sync::mpsc::channel()for received in rx接收两个producer 共享状态并发std::sync::Mutex在多个线程间共享Mutex,使用std::sync::Arc 参考 Rust对多线程…...

力扣 最小路径和
又是一道动态规划基础例题。 题目 这道题可以类似不同路径。先把左上角格子进行填充,然后用一个数组去更新每走到一个格的数字总和,首先处理边界问题,把最左边的列只能由上方的行与原来的格子数值的和,同理,最上方的行…...
Scala中的可变Map操作:简单易懂指南 #Scala Map #Scala
引言 在编程中,Map是一种常见的数据结构,用于存储键值对。Scala提供了不可变Map和可变Map两种类型,它们在处理数据时有不同的特性和用途。本文将通过一个简单的示例,带你了解Scala中可变Map的基本操作,包括添加元素、…...

【go从零单排】XML序列化和反序列化
🌈Don’t worry , just coding! 内耗与overthinking只会削弱你的精力,虚度你的光阴,每天迈出一小步,回头时发现已经走了很远。 📗概念 在 Go 语言中,处理 XML 数据主要使用 encoding/xml 包。这个包提供了…...

在 Oracle Linux 8.9 上安装Oracle Database 23ai 23.5
在 Oracle Linux 8.9 上安装Oracle Database 23ai 23.5 1. 安装 Oracle Database 23ai2. 连接 Oracle Database 23c3. 重启启动后,手动启动数据库4. 重启启动后,手动启动 Listener5. 手动启动 Pluggable Database6. 自动启动 Pluggable Database7. 设置开…...
在 Ubuntu 上安装 `.deb` 软件包有几种方法
在 Ubuntu 上安装 .deb 软件包有几种方法,可以使用命令行工具,也可以通过图形界面进行安装。以下是几种常见的安装方法: 方法 1:使用 dpkg 命令安装 .deb 包 打开终端。 使用 dpkg 命令安装 .deb 包: sudo dpkg -i /…...

一文了解Android本地广播
在 Android 开发中,本地广播(Local Broadcast)是一种轻量级的通信机制,主要用于在同一应用进程内的不同组件之间传递消息,而无需通过系统的全局广播机制。这种方法既可以提高安全性(因为广播仅在应用内传播…...

Ingress nginx 公开TCP服务
文章目录 背景搞起拓展( PROXY Protocol )参考 背景 公司业务繁多, HTTP、GRPC、TCP多种协议服务并存,Kubernetes流量入口复杂,所以萌生了通过LoadBalancer Ingress-nginx 的方式完全的结果入口流量,当然在高并发的场景下可以对…...

谷歌浏览器支持的开发者工具详解
谷歌浏览器(Google Chrome)是全球最受欢迎的网页浏览器之一,它不仅提供了快速、安全的浏览体验,还为开发者提供了强大的开发者工具。本文将详细介绍如何使用谷歌浏览器的开发者工具,并解答一些常见问题。(本…...
【数据结构】汇编 、机器语言 高级语言 简析。
汇编语言、机器语言和高级语言 1. 机器语言(Machine Language) 定义:机器语言是计算机能够直接执行的、用二进制编码的指令集,属于最低级别的编程语言。它由 0 和 1 组成,每条指令由一串二进制数表示。机器语言与计算…...

【青牛科技】GC3901,强势替代 A3901/ALLEGRO应用于摇头机等产品中
在电子工程的浩瀚世界里,不断追求更优性能、更高效率和更低成本的芯片解决方案,是每一位电子工程师的不懈目标。今天,我们要为大家隆重介绍一款足以让你眼前一亮的芯片 —— 芯麦 GC3901,它将以强大的实力成为 A3901/ALLEGRO 的完…...
Java API类与接口:类的转换方法与正则表达式
文章目录 Java包装类的概述对应包装类包装类的转换方法(parse)Integer.parseInt(String s)Long.parseLong(String s)Byte.parseByte(String s)Short.parseShort(String s)Float.parseFloat(String s)Double.parseDouble(String s) 正则表达式常用方法 字符规则. 匹配…...

OceanBase JDBC (Java数据库连接)的概念、分类与兼容性
本章将介绍 OceanBase JDBC的 概念与分类,已帮助使用 JDBC 的用户及技术人员更好的 了解JDBC,以及 OceanBase JDBC在与 MySQL 及 Oracle 兼容性方面的相关能力。 一、JDBC 基础 1.1 JDBC 的概念 JDBC 一般指 Java 数据库连接。Java 数据库连接…...
Linux服务器定时执行jar重启命令
1. sh脚本编写 appNamecvcp-weather PIDps -ef |grep java | grep $appName | grep -v grep | awk {print $2} if [ "$PID" "" ]; thensleep 1;echo "no process";elseecho "process exsits";kill -9 $PID fi sleep 2s nohup /usr/l…...

速览!Win11 22H2/23H2 11月更新补丁KB5046633发布!
系统之家11月13日报道消息,微软为Win11 22H2和23H2用户发布了11月更新补丁KB5046633。此次更新后,系统版本号提升至22621.4460和22631.4460。该补丁包含多项改进和修复,有助于提升用户的使用体验感。想了解完整内容的小伙伴,请继续…...

A day a tweet(sixteen)——The better way of search of ChatGPT
Introducing ChatGPT search a/ad.及时的/及时地 ChatGPT can now search the web in a much better way than before so you get fast, timely a.有关的(relative n.亲戚,亲属;同类事物 a.比较的;相对的) answers with link…...

【网络】HTTP 协议
目录 基本概念基于 HTTP 的系统组成HTTP 的基本性质 HTTP 请求头 & 响应头HTTP 的请求方法HTTP 的返回码HTTP 的 CookieHTTP 缓存 Cache-Control会话HTTP/1.x 的连接管理 基本概念 HTTP(Hypertext Transfer Protocol,超文本传输协议)是一…...
git push报错 unexpected disconnect while reading sideband packet
应该是缓冲不够引起的,可以使用以下命令增加缓存: git config --global http.postBuffer 1048576000 1048576000这里的单位是Byte, 也就是1G。 亲测可以了...

JSX 语法与基础组件使用
在 React Native 中,JSX 是一种 JavaScript 的语法扩展,用于描述 UI 界面。JSX 语法类似于 HTML,但它是 JavaScript 的语法糖,可以直接在 JavaScript 代码中编写 UI 组件。本章节将介绍 JSX 语法的基础知识,以及 React…...

ReactPress:构建高效、灵活、可扩展的开源发布平台
ReactPress Github项目地址:https://github.com/fecommunity/reactpress 欢迎Star。 在当今数字化时代,内容管理系统(CMS)已成为各类网站和应用的核心组成部分。ReactPress,作为一款融合了现代Web开发多项先进技术的开…...
emulator总结
什么是硬件仿真器 做IC设计的人应该都知道软件仿真和FPGA原型验证,可以把硬件仿真器理解为这二者之间的产物,它同时具备二者的优点。 软件仿真(simulator)全面,支持UVM、assert、coverage收集、可以很方便的dump 波形…...

【Docker】‘docker‘ 不是内部或外部命令,也不是可运行的程序 或 批处理文件
在windows 电脑上安装了 Docker Desktop,在控制台输入 docker -v提示报错 ‘docker’ 不是内部或外部命令,也不是可运行的程序 或批处理文件。 报错原因是,环境变量没配置 解决办法,在系统环境变量中配置path ,重新打开cmd 或者…...

Mysql高可用架构方案
Mysql 介绍 Mysql是典型的开源关系型数据库,是许多网站、应用程序、企业软件产品的首选数据库。 Mysql特性: 易于使用,功能强大,支持事务、触发器、存储过程 管理工具多种多样且功能丰富 可以作为千万级数据管理的大型数据库 采…...

Go,15岁了[译]
请点击上方蓝字TonyBai订阅公众号! 虽然迟到了,但绝不缺席!新任Go技术负责人Austin Clements在Go语言15岁生日后的第二天,在Go官方博客上发表了庆祝文章“Go Turns 15[2]”。在这篇文章中,Austin回顾了过去一年Go项目和…...

【大数据学习 | kafka高级部分】kafka的数据同步和数据均衡
1. 数据同步 通过上图我们发现每个分区的数据都不一样,但是三个分区对外的数据却是一致的 这个时候如果第二个副本宕机了 但是如果是leader副本宕机了会发生什么呢? 2. 数据均衡 在线上程序运行的时候,有的时候因为上面副本的损坏ÿ…...
微擎框架php7.4使用phpexcel导出数据报错修复
在使用微擎社区版时,用phpexcel导出数据,提示错误,经过搜索后得知是php版本问题。 之前一直是用的5.6现在改成了7.4。所以才发现了这个问题。 然后去gitee上看了下微擎官方的代码,好像也没有对这个问题进行修复。 找了下&#…...

Netty实现WebSocket Server是否开启压缩深度分析
是否开启压缩会直接影响与客户端是否能够成功握手。 一、具体分析 通常客户端发起与Websocket连接一般是以下形式。 1)包含6个必要的Header Request Headers Sec-WebSocket-Version: 13 Sec-WebSocket-Key: Nlpc0kiHFjRom5/62lj8bA Connection: Upgrade Upgrade…...
【Xrdp联机Ubuntu20.04实用知识点补充】
简单归纳了Xrdp远程连接可能会出现的问题 文章目录 一、网络篇二、Ubuntu远程联机一段时间后莫名奇妙断开Ubuntu20.04禁用休眠配置禁用挂起配置 三、refresh界面频繁刷新四、Authentication is required to create a color profile参考文章总结 一、网络篇 ip addr show eth0接…...

【电脑】解决DiskGenius调整分区大小时报错“文件使用的簇被标记为空闲或与其它文件有交叉”
【电脑】解决DiskGenius调整分区大小时报错“文件使用的簇被标记为空闲或与其它文件有交叉” 零、报错 在使用DiskGenius对磁盘分区进行调整时,DiskGenius检查出磁盘报错,报错信息:文件使用的簇被标记为空闲或与其它文件有交叉,…...

IDC机房服务器托管的费用组成
IDC机房服务器托管的费用,并不是只有我们所想的电费而已,还有一些其它费用组成,详细来看: 1. 机位费用: - 机位费用是根据服务器的尺寸和占用的空间来计算的。服务器通常按照U(Unit)的高度来…...