2016-11-02 5 views
3

私は、チャネルの目的がすべてスレッド間でデータを共有することだと考えました。私はこのコード、based on this exampleを持っている:txは私が間違っていたところ、私は混乱しているmpsc::Sender<(String, String)>Rust mpsc :: Senderはスレッド間で共有できませんか?

error[E0277]: the trait bound `std::sync::mpsc::Sender<(std::string::String, std::string::String)>: std::marker::Sync` is not satisfied 
    --> src/my_module/my_file.rs:137:9 
    | 
137 |   thread::spawn(|| { 
    |   ^^^^^^^^^^^^^ 
    | 
    = note: `std::sync::mpsc::Sender<(std::string::String, std::string::String)>` cannot be shared between threads safely 
    = note: required because of the requirements on the impl of `std::marker::Send` for `&std::sync::mpsc::Sender<(std::string::String, std::string::String)>` 
    = note: required because it appears within the type `[[email protected]/my_module/my_file.rs:137:23: 153:10 res:&&str, ctx:&&my_module::my_submodule::Reader, tx_thread:&std::sync::mpsc::Sender<(std::string::String, std::string::String)>]` 
    = note: required by `std::thread::spawn` 

ある

let tx_thread = tx.clone(); 
let ctx = self; 
thread::spawn(|| { 
    ... 
    let result = ctx.method() 
    tx_thread.send((String::from(result), someOtherString)).unwrap(); 
}) 

。私が間違った場所で探していて、私の問題は実際に私のlet ctx = self;の私の使用でない限り?

+0

'Send'と' Sync'の見通しについては、http://stackoverflow.com/questions/28387421/what-are-examples-of-types-that-implement-only-one-ofを読んでみてください。 -send-and-sync –

答えて

6

送信者スレッド間でを共有することはできませんが、に送信されます。

Sendという特性を実装していますが、Syncを実装していません(同期:スレッド間でSenderへの共有参照に安全にアクセスできます)。

チャネルの設計では、送信者.clone()が送信者を意図しており、スレッドに値として渡します(それぞれのスレッドに対して)。スレッドのクロージャにキーワードmoveがありません。クロージャがクロージャの所有権を取得して変数を取り込むように指示しています。

複数のスレッド間で単一のチャネルエンドポイントを共有する必要がある場合は、mutexでラップする必要があります。 Mutex<Sender<T>>は、Sync + Send where T: Sendです。

興味深い実装上の注意:チャンネルは、1つのプロデューサを持つストリームとして使用するために開始されます。内部データ構造は、送信者が最初に複製されるときにマルチプロデューサ実装にアップグレードされます。

+0

「マルチコンシューマー」ではなく「マルチプロデューサー」であってはなりませんか? – Hauleth

+0

もちろん、ありがとう! – bluss

関連する問題