当前位置:网站首页>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
边栏推荐
- C language loop structure program
- Cross domain settings of Chrome browser -- including new and old versions
- Tensorflow tensor introduction
- Reptile efficiency improvement method
- Operation of 2022 mobile crane driver national question bank simulation examination platform
- 2022江西光伏展,中國分布式光伏展會,南昌太陽能利用展
- I/O多路复用及其相关详解
- Rewrite four functions such as StrCmp in C language
- Random number generation of C #
- Visualization of residential house prices
猜你喜欢
Go language JSON package usage
Cloud native Virtualization: building edge computing instances based on kubevirt
7-21 wrong questions involve knowledge points.
re正则表达式
C1 notes [task training chapter I]
MySQL 中的字符串函数
Implementation of k8s redis one master multi slave dynamic capacity expansion
ArcGIS license error -15 solution
Re regular expression
Cross domain settings of Chrome browser -- including new and old versions
随机推荐
The difference between deep copy and shallow copy
Nanotechnology + AI enabled proteomics | Luomi life technology completed nearly ten million US dollars of financing
Go语言JSON包使用
C language input and output (printf and scanf functions, putchar and getchar functions)
Cloud native Virtualization: building edge computing instances based on kubevirt
Batch export ArcGIS attribute table
Auto.js 自定义对话框
Docker 安装 MySQL
Visualization of residential house prices
Laser slam theory and practice of dark blue College Chapter 3 laser radar distortion removal exercise
Data stream encryption and decryption of C
Using files to save data (C language)
Realization of consumer gray scale
Array rotation
[UDS unified diagnostic service] IV. typical diagnostic service (6) - input / output control unit (0x2F)
An example of linear regression based on tensorflow
2022 Jiangxi energy storage technology exhibition, China Battery exhibition, power battery exhibition and fuel cell Exhibition
Operators in C language
ROS package NMEA_ navsat_ Driver reads GPS and Beidou Positioning Information Notes
2022江西光伏展,中國分布式光伏展會,南昌太陽能利用展