2016-04-09 6 views
5

私は受信チャネルと送信チャネルを保持する構造(実装で後で使用する)を作成するマルチスレッドアプリケーションを作成しています。しかし、私がチャンネルを通じて送信しているタイプには、生涯の指定があります。このタイプはrusts-weboscketライブラリのwebsocket::message:Message です。この仕様のために、糸がスレッドを通過するときに寿命が正確に推測されないようです。Rust Lifetimes with mpsc :: Sender <T<'a>>スレッドとスレッド

は、ここでは、このエラーの錆の遊び場の例です:どこか寿命仕様の問題を https://play.rust-lang.org/?gist=7e37547d1c811185654f10a6a461e1ef&version=stable&backtrace=1

は今、私はスコープに生涯をクロスビームを使用してみましたが、これはその即時の問題を解決しているようだが、実際ただ代表者にelse。私はまさにこの寿命の問題を解決する方法がわからないよ。この時点で https://github.com/aehernandez/Rump/blob/ad717c7ef11857e94d0e1c02539667c8034676c4/src/transport.rs#L199

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

問題の行はこの1つである:私のコードで

私はエラーを取得します。私は他のどこかにそれを委任し続けたくありません。これには良い解決策がありますか?

答えて

3

スレッドを生成すると、潜在的に永遠に存続する可能性があります。あなたのTransport<'a>タイプの生存期間は'aで、'static以外のものは確実に残ります(ただし、エラーメッセージは非常に混乱します)。クロージャを使用して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 `[[email protected]<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

関連する問題