Rust mpsc::Sender cannot be shared between threads?

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.

You may use std::sync::mpsc::SyncSender from the standard library. The diffrenece is that it implements the Sync trait but it will may block if there is no space in the internal buffer while sending a message.

For more information:

Leave a Comment