当前位置:网站首页>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
边栏推荐
- How to read literature
- Crawling mobile game website game details and comments (MQ + multithreading)
- Implementation of k8s redis one master multi slave dynamic capacity expansion
- MySQL auto start settings start with systemctl start mysqld
- A few lines of code teach you to crawl lol skin pictures
- Nat commun | current progress and open challenges of applied deep learning in Bioscience
- ES6
- C1 notes [task training part 2]
- Scikit learn sklearn 0.18 official document Chinese version
- C#的随机数生成
猜你喜欢
Operation of 2022 mobile crane driver national question bank simulation examination platform
Fashion classification case based on keras
An example of linear regression based on tensorflow
Logic regression principle and code implementation
JS get link? The following parameter name or value, according to the URL? Judge the parameters after
Qtablewidget usage explanation
positioner
Docker 安装 Redis
Eigen learning summary
Batch export ArcGIS attribute table
随机推荐
Qt读写XML文件(含源码+注释)
[UDS unified diagnostic service] IV. typical diagnostic service (6) - input / output control unit (0x2F)
Docker 安装 Redis
Identification verification code
YOLOv4剪枝【附代码】
Go对文件操作
Selenium + webdriver + chrome realize Baidu to search for pictures
2022 Jiangxi Photovoltaic Exhibition, China distributed Photovoltaic Exhibition, Nanchang solar energy utilization Exhibition
C#的随机数生成
Reptile efficiency improvement method
ArcGIS table to excel exceeds the upper limit, conversion failed
word frequency count
Data stream encryption and decryption of C
Auto.js 自定义对话框
Excel opens large CSV format data
Read excel, int digital time to time
MySQL 中的字符串函数
Solving the problem of displaying too many unique values in ArcGIS partition statistics failed
MySQL auto start settings start with systemctl start mysqld
I/O多路复用及其相关详解