当前位置:网站首页>Rust:在线程池中共享变量
Rust:在线程池中共享变量
2022-04-23 05:45:00 【许野平】
Rust:在线程池中共享变量
1 最简单的试验
声明一个只读的局部变量,在线程池共享,代码如下:
use std::thread;
fn work(data: &String) {
}
fn main() {
let s = "hello".to_string();
for _ in 0..10 {
thread::spawn(|| work(&s));
}
}
编译错误提示:
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`
错误信息说,闭包的生命周期,可能比借用的变量 s 的生命周期还长。因此,在线程池借用局部变量是无法编译过去的。
2 闭包中使用局部变量,move 还是 borrow?
既然借用局部变量行不通,我就来个所有权转移行不行?
use std::thread;
fn work(data: String) {
}
fn main() {
let s = "hello".to_string();
for _ in 0..10 {
thread::spawn(|| work(s.clone()));
}
}
结果还是报错:
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`
|
还是认为 s 被借用了。我分析原因,只要 s 出现在闭包中,如果闭包有 move 修饰,就算是所有权转移,如果没有 move 修饰,就算是被借用了(不知理解是否正确)。可以把闭包看作是一个运算式或者函数,只要其中出现了变量 s,就算借用了s,就是把 s 改成 (&s) 也不行。
既然如此,代码修改如下,编译成功:
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 使用智能指针 Arc,共享局部变量
但这样一来,就没有共享了。于是乎,想到了 Arc 这个智能指针,实现了局部变量的线程池共享。
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 只读共享全局变量
如果变量是只读共享,Arc 还是略有麻烦,最好的办法还是用全局变量共享。于是代码修改如下:
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));
}
}
错误信息如下:
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
说是可修改的全局变量被引用时,必须用 unsafe 修饰。我有些崩溃了,看样子想在 rust 中高效只读共享全局变量,也必须的 unsafe 才行。
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));
}
}
}
版权声明
本文为[许野平]所创,转载请带上原文链接,感谢
https://yeping.blog.csdn.net/article/details/123197232
边栏推荐
猜你喜欢
Solution to the trial of ycu Blue Bridge Cup programming competition in 2021
SQL -- data filtering and grouping
Export of data
检测技术与原理
Cf1427c the hard work of paparazzi
How SYSTEMd uses / etc / init D script
P1586 solution to tetragonal theorem
Addition, deletion, modification and query of MySQL table
C language file operation
Advanced operation of idea debug
随机推荐
Kibana search syntax
SVN简单操作命令
LockSupport. Park and unpark, wait and notify
Integers have friends interval GCD + double pointer
Rust 中的 RefCell
Example of ticket selling with reentrant lock
Optional best practices
Cf6d lizards and fundamentals 2 problem solving
4. Print form
Advanced operation of idea debug
日志
爬取蝉妈妈数据平台商品数据
Techniques et principes de détection
Common sense of thread pool
Best practices for MySQL storage time
Event listener
Stability building best practices
NVIDIA Jetson: GStreamer 和 openMAX(gst-omx) 插件
Understanding and installing MySQL
10.Advance Next Round