Lifetime of variables passed to a new thread

前端 未结 1 1976
陌清茗
陌清茗 2020-11-29 13:44

I have trouble compiling this program:

use std::env;
use std::sync::mpsc;
use std::thread;
use std::time::Duration;

fn main() {
    let args: Vec<_> =         


        
相关标签:
1条回答
  • 2020-11-29 14:00

    The problem lies in spawning a background thread. When you call thread::spawn you effectively have to pass ownership of any resource used in it to the thread, as it might run indefinitely, which means that its lifetime must be 'static.

    There are two options to resolve that: the simplest one would be to pass ownership. Your code here

    let new_arg = arg.to_string() + "foo";
    t.send(arg);
    

    looks like you actually wanted to send new_arg, in which case you could just create the owned result of arg.to_string() before spawning the thread, thus eliminating the need to pass the reference arg.

    Another slightly more involved idea, that might be useful at some point though, are scoped threads as implemented in crossbeam for example. These are bound to an explicit scope, where you spawn them and are joined together at the end. This looks somewhat like this:

    crossbeam::scope(|scope| {
        scope.spawn(|| {
            println!("Hello from a scoped thread!");
        });
    });
    

    Have a look at the docs for further details.

    0 讨论(0)
提交回复
热议问题