How can I send non-static data to a thread in Rust

2020-05-06 09:57发布

I am trying to fire up a new thread using some heap data in Rust and I am getting a bunch of errors that stem from the need of the data to have 'static lifetime. I've worked my way backwards up my program but hit a problem.

use std::sync::Arc;
use std::thread;

struct ThreadData {
    vector_of_strings: Vec<String>,
    terms: Vec<&'static str>,
    quotient: usize,
}

fn perform_search(slice: &[String], terms: &[&str]) {
    /* ... */
}

fn threaded_search(td_arc: &Arc<ThreadData>) {
    let no_of_lines = td_arc.vector_of_strings.len();
    let new_tda1 = td_arc.clone();

    let strings_as_slice1 = new_tda1.vector_of_strings.as_slice();   

    thread::spawn(move || {
        perform_search(&strings_as_slice1[0..td_arc.quotient], &new_tda1.terms);
    });
}

fn main() {
    let td = ThreadData {
        vector_of_strings: Vec::new(),
        terms: Vec::new(),
        quotient: 0,
    };

    let td_arc = Arc::new(td);
    threaded_search(&td_arc);
}

Error:

error[E0621]: explicit lifetime required in the type of `td_arc`               
  --> src/main.rs:20:5                                                         
   |                                                                           
14 | fn threaded_search(td_arc: &Arc<ThreadData>) {                            
   |                            ---------------- help: add explicit lifetime `'static` to the type of `td_arc`: `&'static std::sync::Arc<ThreadData>`
...                                                                            
20 |     thread::spawn(move || {                                               
   |     ^^^^^^^^^^^^^ lifetime `'static` required

1条回答
Animai°情兽
2楼-- · 2020-05-06 10:44

The error about 'static is because the new thread created within thread::spawn may outlive the invocation of threaded_search during which the thread is initially created, which means the thread must not be permitted to use any local variables from threaded_search with a lifetime shorter than 'static.

In your code the new thread is referring to strings_as_slice1 and td_arc.

Generally with thread::spawn and Arc you will want to move ownership of one reference count into the thread and have the thread access whatever it needs through that reference counted pointer rather than from the enclosing short-lived scope directly.

fn threaded_search(td_arc: &Arc<ThreadData>) {
    // Increment reference count that we can move into the new thread.
    let td_arc = td_arc.clone();

    thread::spawn(move || {
        perform_search(&td_arc.vector_of_strings[0..td_arc.quotient], &td_arc.terms);
    });
}
查看更多
登录 后发表回答