Rust生活时间与mpsc :: Sender <T <'a >>和线程

ala*_*inh 5 multithreading rust

我正在创建一个多线程应用程序,我在其中创建一个接收通道和一个用于保存发送通道的结构(稍后将由实现使用).但是,我通过通道发送的类型具有生命周期规范.这种类型websocket::message:Message 来自rusts-weboscket库.由于这个规范,当它通过线程时,生锈似乎无法正确地推断生命周期.

以下是此错误的生锈操场示例:https: //play.rust-lang.org/?gist = 7e37547d1c811185654f10a6a461e1ef&version = stable&backtrace = 1

现在,我尝试使用crossbeam来规范生命周期,这似乎解决了这个直接的问题,但实际上只是委托其他地方的生命周期规范问题.

在我的代码中,我收到错误:

   $ cargo check
   Compiling rump v0.1.0 (file:///home/alainh/UPenn/CIS198/Rump)
transport.rs:200:42: 200:57 error: cannot infer an appropriate lifetime for autoref due to conflicting requirements [E0495]
transport.rs:200         self.sender.send(self.serializer.encode(message));
                                                          ^~~~~~~~~~~~~~~
transport.rs:199:5: 202:6 help: consider using an explicit lifetime parameter as shown: fn send<T: Encodable>(&'a mut self, message: &T) -> WampResult<()>
transport.rs:199     fn send<T: Encodable>(&mut self, message: &T) -> WampResult<()> {
transport.rs:200         self.sender.send(self.serializer.encode(message));
transport.rs:201         Ok(())
transport.rs:202     }
error: aborting due to previous error
Could not compile `rump`.
Run Code Online (Sandbox Code Playgroud)

有问题的一行是这一行:https: //github.com/aehernandez/Rump/blob/ad717c7ef11857e94d0e1c02539667c8034676c4/src/transport.rs#L199

在这一点上,我不确定如何解决这个终身问题.我不想继续把它委托给其他地方.有一个很好的解决方案吗?

Djz*_*zin 3

当您生成一个线程时,它可能会永远存在;除了(尽管错误消息非常令人困惑)之外,肯定比您的Transport<'a>类型的任何生命周期都长。当您使用闭包进行调用时,该闭包必须具有生命周期,只有在以下情况下才是正确的:'a'staticthread::spawn'static'a == 'static

由于您实际上并未通过通道发送具有生命周期的对象,因此请考虑'static显式使用生命周期:

impl Connector for Transport<'static> {
    ...
}
Run Code Online (Sandbox Code Playgroud)

婴儿围栏

编辑:

手动注释发送者和接收者的类型

    let (tx, rx): (mpsc::Sender<Message<'a>>, mpsc::Receiver<Message<'a>>) = mpsc::channel();
    let tx_send: mpsc::Sender<Message<'a>> = tx.clone();
Run Code Online (Sandbox Code Playgroud)

向您展示了一个更明智的错误

<anon>:27:22: 27:35 error: the type `[closure@<anon>:27:36: 29:10 tx_send:std::sync::mpsc::Sender<Message<'a>>]` does not fulfill the required lifetime [E0477]
<anon>:27         let handle = thread::spawn(move || {
                               ^~~~~~~~~~~~~
note: type must outlive the static lifetime
error: aborting due to previous error
playpen: application terminated with error code 101
Run Code Online (Sandbox Code Playgroud)

婴儿围栏