Lifetime woes when using threads

后端 未结 1 870
无人及你
无人及你 2021-01-05 15:41

I\'m having a hard time getting this to compile:

use std::thread::{self, JoinHandle};

struct Foo<\'c> {
    foo: &\'c str,
}

impl<\'c> Foo&         


        
1条回答
  •  一生所求
    2021-01-05 16:22

    The lifetime constraint that is causing this problem is the one in Thread::spawn, which requires the FnOnce closure to be Send. Send requires 'static, which means that the data contains no non-'static data. Your data, Foo, contains a borrowed str, which is not 'static, which makes Foo non-'static. As a result, you can't send Foo across threads.

    Why is this? Since Foo contains a borrow, it is valid for only a small lifetime. If Rust allowed you to send an instance of Foo to another thread, then that thread could easily use Foo long after the data it borrows has become invalid.

    You might think that this is actually overly restrictive, and you'd be right. There's no reason to not allow local parallelism as long as you can prove to the borrow checker that the thread terminates within some lifetime. There are currently no constructs in Rust to do this, but there are some future solutions for this problem, such as this RFC which extends the Send trait to allow local parallelism.

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