Using Message Passing to Transfer Data Between Threads

One increasingly popular approach to ensuring safe concurrency is message passing, where threads or actors communicate by sending each other messages containing data. Here’s the idea in a slogan from the Go language documentation: “Do not communicate by sharing memory; instead, share memory by communicating.”

To accomplish message-sending concurrency, Rust's standard library provides an implementation of channels. A channel is a general programming concept by which data is sent from one thread to another.

You can imagine a channel in programming as being like a directional channel of water, such as a stream or a river. If you put something like a rubber duck into a river, it will travel downstream to the end of the waterway.

A channel has two halves: a transmitter and a receiver. The transmitter half is the upstream location where you put rubber ducks into the river, and the receiver half is where the rubber duck ends up downstream. One part of your code calls methods on the transmitter with the data you want to send, and another part checks the receiving end for arriving messages. A channel is said to be closed if either the transmitter or receiver half is dropped.

Here, we’ll work up to a program that has one thread to generate values and send them down a channel, and another thread that will receive the values and print them out. We’ll be sending simple values between threads using a channel to illustrate the feature. Once you’re familiar with the technique, you could use channels for any threads that need to communicate between each other, such as a chat system or a system where many threads perform parts of a calculation and send the parts to one thread that aggregates the results.

First, in Listing 16-6, we’ll create a channel but not do anything with it. Note that this won’t compile yet because Rust can’t tell what type of values we want to send over the channel.

Filename: src/main.rs

  1. use std::sync::mpsc;
  2. fn main() {
  3. let (tx, rx) = mpsc::channel();
  4. }

Listing 16-6: Creating a channel and assigning the two halves to tx and rx

We create a new channel using the mpsc::channel function; mpsc stands for multiple producer, single consumer. In short, the way Rust’s standard library implements channels means a channel can have multiple sending ends that produce values but only one receiving end that consumes those values. Imagine multiple streams flowing together into one big river: everything sent down any of the streams will end up in one river at the end. We’ll start with a single producer for now, but we’ll add multiple producers when we get this example working.

The mpsc::channel function returns a tuple, the first element of which is the sending end—the transmitter—and the second element is the receiving end—the receiver. The abbreviations tx and rx are traditionally used in many fields for transmitter and receiver respectively, so we name our variables as such to indicate each end. We’re using a let statement with a pattern that destructures the tuples; we’ll discuss the use of patterns in let statements and destructuring in Chapter 18. For now, know that using a let statement this way is a convenient approach to extract the pieces of the tuple returned by mpsc::channel.

Let’s move the transmitting end into a spawned thread and have it send one string so the spawned thread is communicating with the main thread, as shown in Listing 16-7. This is like putting a rubber duck in the river upstream or sending a chat message from one thread to another.

Filename: src/main.rs

  1. use std::sync::mpsc;
  2. use std::thread;
  3. fn main() {
  4. let (tx, rx) = mpsc::channel();
  5. thread::spawn(move || {
  6. let val = String::from("hi");
  7. tx.send(val).unwrap();
  8. });
  9. }

Listing 16-7: Moving tx to a spawned thread and sending “hi”

Again, we’re using thread::spawn to create a new thread and then using move to move tx into the closure so the spawned thread owns tx. The spawned thread needs to own the transmitter to be able to send messages through the channel. The transmitter has a send method that takes the value we want to send. The send method returns a Result type, so if the receiver has already been dropped and there’s nowhere to send a value, the send operation will return an error. In this example, we’re calling unwrap to panic in case of an error. But in a real application, we would handle it properly: return to Chapter 9 to review strategies for proper error handling.

In Listing 16-8, we’ll get the value from the receiver in the main thread. This is like retrieving the rubber duck from the water at the end of the river or receiving a chat message.

Filename: src/main.rs

  1. use std::sync::mpsc;
  2. use std::thread;
  3. fn main() {
  4. let (tx, rx) = mpsc::channel();
  5. thread::spawn(move || {
  6. let val = String::from("hi");
  7. tx.send(val).unwrap();
  8. });
  9. let received = rx.recv().unwrap();
  10. println!("Got: {}", received);
  11. }

Listing 16-8: Receiving the value “hi” in the main thread and printing it

The receiver has two useful methods: recv and try_recv. We’re using recv, short for receive, which will block the main thread’s execution and wait until a value is sent down the channel. Once a value is sent, recv will return it in a Result. When the transmitter closes, recv will return an error to signal that no more values will be coming.

The try_recv method doesn’t block, but will instead return a Result immediately: an Ok value holding a message if one is available and an Err value if there aren’t any messages this time. Using try_recv is useful if this thread has other work to do while waiting for messages: we could write a loop that calls try_recv every so often, handles a message if one is available, and otherwise does other work for a little while until checking again.

We’ve used recv in this example for simplicity; we don’t have any other work for the main thread to do other than wait for messages, so blocking the main thread is appropriate.

When we run the code in Listing 16-8, we’ll see the value printed from the main thread:

  1. Got: hi

Perfect!

Channels and Ownership Transference

The ownership rules play a vital role in message sending because they help you write safe, concurrent code. Preventing errors in concurrent programming is the advantage of thinking about ownership throughout your Rust programs. Let’s do an experiment to show how channels and ownership work together to prevent problems: we’ll try to use a val value in the spawned thread after we’ve sent it down the channel. Try compiling the code in Listing 16-9 to see why this code isn’t allowed:

Filename: src/main.rs

  1. use std::sync::mpsc;
  2. use std::thread;
  3. fn main() {
  4. let (tx, rx) = mpsc::channel();
  5. thread::spawn(move || {
  6. let val = String::from("hi");
  7. tx.send(val).unwrap();
  8. println!("val is {}", val);
  9. });
  10. let received = rx.recv().unwrap();
  11. println!("Got: {}", received);
  12. }

Listing 16-9: Attempting to use val after we’ve sent it down the channel

Here, we try to print val after we’ve sent it down the channel via tx.send. Allowing this would be a bad idea: once the value has been sent to another thread, that thread could modify or drop it before we try to use the value again. Potentially, the other thread’s modifications could cause errors or unexpected results due to inconsistent or nonexistent data. However, Rust gives us an error if we try to compile the code in Listing 16-9:

  1. $ cargo run
  2. Compiling message-passing v0.1.0 (file:///projects/message-passing)
  3. error[E0382]: borrow of moved value: `val`
  4. --> src/main.rs:10:31
  5. |
  6. 8 | let val = String::from("hi");
  7. | --- move occurs because `val` has type `String`, which does not implement the `Copy` trait
  8. 9 | tx.send(val).unwrap();
  9. | --- value moved here
  10. 10 | println!("val is {}", val);
  11. | ^^^ value borrowed here after move
  12. |
  13. = note: this error originates in the macro `$crate::format_args_nl` (in Nightly builds, run with -Z macro-backtrace for more info)
  14. For more information about this error, try `rustc --explain E0382`.
  15. error: could not compile `message-passing` due to previous error

Our concurrency mistake has caused a compile time error. The send function takes ownership of its parameter, and when the value is moved, the receiver takes ownership of it. This stops us from accidentally using the value again after sending it; the ownership system checks that everything is okay.

Sending Multiple Values and Seeing the Receiver Waiting

The code in Listing 16-8 compiled and ran, but it didn’t clearly show us that two separate threads were talking to each other over the channel. In Listing 16-10 we’ve made some modifications that will prove the code in Listing 16-8 is running concurrently: the spawned thread will now send multiple messages and pause for a second between each message.

Filename: src/main.rs

  1. use std::sync::mpsc;
  2. use std::thread;
  3. use std::time::Duration;
  4. fn main() {
  5. let (tx, rx) = mpsc::channel();
  6. thread::spawn(move || {
  7. let vals = vec![
  8. String::from("hi"),
  9. String::from("from"),
  10. String::from("the"),
  11. String::from("thread"),
  12. ];
  13. for val in vals {
  14. tx.send(val).unwrap();
  15. thread::sleep(Duration::from_secs(1));
  16. }
  17. });
  18. for received in rx {
  19. println!("Got: {}", received);
  20. }
  21. }

Listing 16-10: Sending multiple messages and pausing between each

This time, the spawned thread has a vector of strings that we want to send to the main thread. We iterate over them, sending each individually, and pause between each by calling the thread::sleep function with a Duration value of 1 second.

In the main thread, we’re not calling the recv function explicitly anymore: instead, we’re treating rx as an iterator. For each value received, we’re printing it. When the channel is closed, iteration will end.

When running the code in Listing 16-10, you should see the following output with a 1-second pause in between each line:

  1. Got: hi
  2. Got: from
  3. Got: the
  4. Got: thread

Because we don’t have any code that pauses or delays in the for loop in the main thread, we can tell that the main thread is waiting to receive values from the spawned thread.

Creating Multiple Producers by Cloning the Transmitter

Earlier we mentioned that mpsc was an acronym for multiple producer, single consumer. Let’s put mpsc to use and expand the code in Listing 16-10 to create multiple threads that all send values to the same receiver. We can do so by cloning the transmitter, as shown in Listing 16-11:

Filename: src/main.rs

  1. use std::sync::mpsc;
  2. use std::thread;
  3. use std::time::Duration;
  4. fn main() {
  5. // --snip--
  6. let (tx, rx) = mpsc::channel();
  7. let tx1 = tx.clone();
  8. thread::spawn(move || {
  9. let vals = vec![
  10. String::from("hi"),
  11. String::from("from"),
  12. String::from("the"),
  13. String::from("thread"),
  14. ];
  15. for val in vals {
  16. tx1.send(val).unwrap();
  17. thread::sleep(Duration::from_secs(1));
  18. }
  19. });
  20. thread::spawn(move || {
  21. let vals = vec![
  22. String::from("more"),
  23. String::from("messages"),
  24. String::from("for"),
  25. String::from("you"),
  26. ];
  27. for val in vals {
  28. tx.send(val).unwrap();
  29. thread::sleep(Duration::from_secs(1));
  30. }
  31. });
  32. for received in rx {
  33. println!("Got: {}", received);
  34. }
  35. // --snip--
  36. }

Listing 16-11: Sending multiple messages from multiple producers

This time, before we create the first spawned thread, we call clone on the transmitter. This will give us a new transmitter we can pass to the first spawned thread. We pass the original transmitter to a second spawned thread. This gives us two threads, each sending different messages to the one receiver.

When you run the code, your output should look something like this:

  1. Got: hi
  2. Got: more
  3. Got: from
  4. Got: messages
  5. Got: for
  6. Got: the
  7. Got: thread
  8. Got: you

You might see the values in another order, depending on your system. This is what makes concurrency interesting as well as difficult. If you experiment with thread::sleep, giving it various values in the different threads, each run will be more nondeterministic and create different output each time.

Now that we’ve looked at how channels work, let’s look at a different method of concurrency.