当前位置:网站首页>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