当前位置:网站首页>Rust: shared variable in thread pool
Rust: shared variable in thread pool
2022-04-23 18:03:00 【Xu Yeping】
Rust: Shared variables in the thread pool
1 The simplest experiment
Declare a read-only local variable , Online process pool sharing , The code is as follows :
use std::thread;
fn work(data: &String) {
}
fn main() {
let s = "hello".to_string();
for _ in 0..10 {
thread::spawn(|| work(&s));
}
}
Compile error prompt :
error[E0373]: closure may outlive the current function, but it borrows `s`, which is owned by the current function
--> src\main.rs:9:23
|
9 | thread::spawn(|| work(&s));
| ^^ - `s` is borrowed here
| |
| may outlive borrowed value `s`
|
note: function requires argument type to outlive `'static`
Error message theory , The life cycle of closure , May be better than borrowed variables s The life cycle of is still long . therefore , The past cannot be compiled by borrowing local variables from the thread pool .
2 Use local variables in closures ,move still borrow?
Since borrowing local variables doesn't work , Can I have a transfer of ownership ?
use std::thread;
fn work(data: String) {
}
fn main() {
let s = "hello".to_string();
for _ in 0..10 {
thread::spawn(|| work(s.clone()));
}
}
The result is still wrong :
error[E0373]: closure may outlive the current function, but it borrows `s`, which is owned by the current function
--> src\main.rs:9:23
|
9 | thread::spawn(|| work(s.clone()));
| ^^ - `s` is borrowed here
| |
| may outlive borrowed value `s`
|
Still think s Borrowed . I analyze the reasons , as long as s Appear in closures , If the closure has move modification , Even if it's a transfer of ownership , without move modification , Even if it's borrowed ( I wonder if the understanding is correct ). You can think of a closure as an expression or function , As long as there are variables in it s, Even if you borrow s, Is to put s Change to (&s) Not good either. .
In that case , The code is modified as follows , Compile successfully :
use std::thread;
fn work(data: String) {
}
fn main() {
let s = "hello".to_string();
for _ in 0..10 {
let t = s.clone();
thread::spawn(|| work(t));
}
}
3 Use smart pointer Arc, Shared local variables
But this way , There is no sharing . So , Think of the Arc This smart pointer , The thread pool sharing of local variables is realized .
use std::sync::Arc;
use std::thread;
fn work(t: Arc<String>) {
}
fn main() {
let s = Arc::new("hello".to_string());
for _ in 0..10 {
let p = s.clone();
thread::spawn(move|| work(p));
}
}
4 Read only shared global variables
If the variable is read-only shared ,Arc Still a little trouble , The best way is to share with global variables . So the code is modified as follows :
use std::thread;
fn work(data: &String) {
}
fn main() {
static mut s: String = String::new();
s = "hello".to_string();
for _ in 0..10 {
thread::spawn(|| work(&s));
}
}
The error message is as follows :
error[E0133]: use of mutable static is unsafe and requires unsafe function or block
--> src\main.rs:9:31
|
9 | thread::spawn(|| work(&s));
| ^^ use of mutable static
|
= note: mutable statics can be mutated by multiple threads: aliasing violations or data races will cause undefined behavior
When a modifiable global variable is referenced , Must use unsafe modification . I'm a little broken , It seems that I want to rust Efficient read-only shared global variables in , It's also necessary unsafe Talent .
use std::thread;
fn work(data: &String) {
}
fn main() {
static mut s: String = String::new();
unsafe {
s = "hello".to_string();
for _ in 0..10 {
thread::spawn(|| work(&s));
}
}
}
版权声明
本文为[Xu Yeping]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230544498360.html
边栏推荐
- Re regular expression
- ROS package NMEA_ navsat_ Driver reads GPS and Beidou Positioning Information Notes
- MySQL_ 01_ Simple data retrieval
- Crawler for querying nicknames and avatars based on qqwebapi
- Build openstack platform
- 2022 Shanghai safety officer C certificate operation certificate examination question bank and simulation examination
- Multi thread crawling Marco Polo network supplier data
- C language input and output (printf and scanf functions, putchar and getchar functions)
- Welcome to the markdown editor
- Gaode map search, drag and drop query address
猜你喜欢

Clion installation tutorial

2022 Shanghai safety officer C certificate operation certificate examination question bank and simulation examination

Go对文件操作

云原生虚拟化:基于 Kubevirt 构建边缘计算实例

2022 Jiangxi energy storage technology exhibition, China Battery exhibition, power battery exhibition and fuel cell Exhibition
![[UDS unified diagnostic service] IV. typical diagnostic service (6) - input / output control unit (0x2F)](/img/ae/cbfc01fbcc816915b1794a9d70247a.png)
[UDS unified diagnostic service] IV. typical diagnostic service (6) - input / output control unit (0x2F)

Qt读写XML文件(含源码+注释)

2022江西光伏展,中国分布式光伏展会,南昌太阳能利用展

Map basemap Library

Implementation of object detection case based on SSD
随机推荐
C byte array (byte []) and string are converted to each other
cartographer_ There is no problem compiling node, but running the bug that hangs directly
Yolov4 pruning [with code]
Identification verification code
Crack sliding verification code
Gobang game based on pyGame Library
C language array processing batch data
Cloud native Virtualization: building edge computing instances based on kubevirt
JS get link? The following parameter name or value, according to the URL? Judge the parameters after
SSD硬盘SATA接口和M.2接口区别(详细)总结
MySQL_01_简单数据检索
Nat commun | current progress and open challenges of applied deep learning in Bioscience
Flash operates on multiple databases
I / O multiplexing and its related details
Read excel, int digital time to time
Halo open source project learning (II): entity classes and data tables
Realization of consumer gray scale
C#字节数组(byte[])和字符串相互转换
Reptile efficiency improvement method
Map basemap Library