Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rust mpsc::Sender cannot be shared between threads?

I thought the whole purpose of a channel was to share data between threads. I have this code, based on this example:

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

Where tx is a mpsc::Sender<(String, String)>

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 `[closure@src/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`

I'm confused where I went wrong. Unless I'm looking in the wrong place and my issue is actually my use of let ctx = self;?

like image 572
Christian Grabowski Avatar asked Nov 02 '16 15:11

Christian Grabowski


1 Answers

Sender cannot be shared between threads, but it can be sent!

It implements the trait Send but not Sync (Sync: Safe to access shared reference to Sender across threads).

The design of channels intends that you .clone() the sender and pass it as a value to a thread (for each thread you have). You are missing the move keyword on the thread's closure, which instructs the closure to capture variables by taking ownership of them.

If you must share a single channel endpoint between several threads, it must be wrapped in a mutex. Mutex<Sender<T>> is Sync + Send where T: Send.

Interesting implementation note: The channel starts out for use as a stream where it has a single producer. The internal data structures are upgraded to a multi-producer implementation the first time a sender is cloned.

like image 169
bluss Avatar answered Sep 19 '22 12:09

bluss