【问题标题】:Rust Lifetimes with mpsc::Sender<T<'a>> and threadsRust Lifetimes with mpsc::Sender<T<'a>> 和线程
【发布时间】:2016-04-09 00:24:13
【问题描述】:

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

下面是这个错误的一个 rust playground 示例: https://play.rust-lang.org/?gist=7e37547d1c811185654f10a6a461e1ef&version=stable&backtrace=1

现在,我尝试使用横梁来确定生命周期的范围,这似乎解决了当前的问题,但实际上只是将生命周期规范问题委托给了其他地方。

在我的代码中出现错误:

   $ 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`.

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

在这一点上,我不确定如何准确解决这个终身问题。我不想继续将其委托给其他地方。有什么好的解决办法吗?

【问题讨论】:

    标签: multithreading rust


    【解决方案1】:

    当你产生一个线程时,它可能永远存在;除了'static 之外,肯定比你的Transport&lt;'a&gt; 类型更长寿'a(尽管错误消息非常令人困惑)。当您使用闭包调用 thread::spawn 时,该闭包必须具有 'static 生命周期,这仅在 'a == 'static 时才成立。

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

    impl Connector for Transport<'static> {
        ...
    }
    

    Playpen

    编辑:

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

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

    向您显示一个更明智的错误

    <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
    

    Playpen

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-09
      • 1970-01-01
      • 2021-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多