What's the best way to send a message between threads

Hi all,
This question has a simple subject but I've not been able to find an answer that suits. I've been using Rust for a little while now and have worked with the standard library's channels so have some understanding of them. I've asked this question on StackOverflow but I think I'm not asking the question correctly or I'm just not asking the question in the right place.

I have a program with many threads in it. Thread A needs to send a message to thread B and thread A has nothing setup to be able to do this. My curren pattern to facilitate this is to have a lazy static that contains the sender for thread B's channel and thread A can clone the sender when required.

Is my current pattern acceptable?
How can this be achieved in Rust?
(please feel free to tell me if my question is not clear enough)

Using global variables for this isn't ideal because of all the usual reasons for global variables not being ideal (hard-coded dependencies, hard to test, you can't just look at your function arguments to see what state the app is touching, etc.).

Instead, I think you've touched on the main problem...

At the start of your program you should set up the communication mechanism (e.g. by calling std::sync::mpsc::channel()) and then pass each end of the channel to the thread.

Here is some pseudocode to explain what I mean:

fn main() {
  let (tx, rx) = std::sync::mpsc::channel();

  std::thread::spawn(move || { 
    let result = do_thread_a_stuff();
    tx.send(result);
  });

  std::thread::spawn(move || {
    for result in rx {
      do_thread_b_stuff(result);
    }
  });
}

That way even if the code being used to produce/consume results in threads A and B that isn't aware of communication (e.g. because it's from a dependency), you can still wrap them in a function which is aware of the communication mechanism.

6 Likes

By far the best way is to use crossbeam-channel. It's more flexible and much faster than std::mpsc.

3 Likes

Thanks for the reply. I'll look at implementing programs like this in the future.

Some of the rustlings exercises, namely arc1.rs and the threads exercises try to guide you through what you’re asking about. The section on message passing in The Book really helped me. This also really helped me get my head around it.