当前位置:网站首页>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
边栏推荐
- Click Cancel to return to the previous page and modify the parameter value of the previous page, let pages = getcurrentpages() let prevpage = pages [pages. Length - 2] / / the data of the previous pag
- MySQL auto start settings start with systemctl start mysqld
- Remember using Ali Font Icon Library for the first time
- C language loop structure program
- Cross domain settings of Chrome browser -- including new and old versions
- Solving the problem of displaying too many unique values in ArcGIS partition statistics failed
- 2022 Jiangxi Photovoltaic Exhibition, China distributed Photovoltaic Exhibition, Nanchang solar energy utilization Exhibition
- Using files to save data (C language)
- Crawl lottery data
- ES6 face test questions (reference documents)
猜你喜欢

Implementation of object detection case based on SSD

MySQL auto start settings start with systemctl start mysqld

Fashion classification case based on keras

Gaode map search, drag and drop query address

The ultimate experience, the audio and video technology behind the tiktok

An example of linear regression based on tensorflow

Cross domain settings of Chrome browser -- including new and old versions

Docker 安裝 Redis

C1小笔记【任务训练篇一】

云原生虚拟化:基于 Kubevirt 构建边缘计算实例
随机推荐
C1 notes [task training chapter I]
Process management command
Nat commun | current progress and open challenges of applied deep learning in Bioscience
Cross domain settings of Chrome browser -- including new and old versions
C language to achieve 2048 small game direction merging logic
Solving the problem of displaying too many unique values in ArcGIS partition statistics failed
C language array processing batch data
C#字节数组(byte[])和字符串相互转换
Crawl the product data of Xiaomi Youpin app
xlsxwriter. exceptions. Filecreateerror: [errno 13] permission denied
Dock installation redis
[UDS unified diagnostic service] v. diagnostic application example: Flash bootloader
极致体验,揭晓抖音背后的音视频技术
Go语言JSON包使用
JS high frequency interview questions
C language input and output (printf and scanf functions, putchar and getchar functions)
读取excel,int 数字时间转时间
Array rotation
2022 tea artist (primary) examination simulated 100 questions and simulated examination
C# 网络相关操作