πŸ“¨
World 16 Β· Doing Many Things at Once

Sending Notes (Channels)

Helpers are great, but how do they talk to each other? In Rust, threads can send messages through a channel β€” like passing a note from one desk to another. πŸ“¨

The Big Idea A channel lets one thread send a message and another thread receive it. One end sends, the other end gets β€” safely and in order.

A walkie-talkie for threads

When you make a channel, you get two ends:

  • tx β€” the transmitter, the part that sends (think: β€œtalk”).
  • rx β€” the receiver, the part that gets the message (think: β€œreceive”).
Think of it like this… A channel is a pair of walkie-talkies. πŸ“» One thread presses the button and speaks (tx.send), and the other thread hears it (rx.recv).

Sending one message

We make a channel with channel(). A helper thread sends a number with tx.send. Back in main, rx.recv() waits for the message and hands it to us.

The word move lets the helper take the tx end with it. Then rx.recv() patiently waits until a message arrives. When the 42 shows up, we print it! πŸŽ‰

Ferris says: recv is patient β€” it waits and waits until a note arrives, so you don't have to keep checking. πŸ¦€
Try this! Change secret to your favorite number and press β–Ά Run. Can you send a word in quotes like "hello" instead of a number?

Quick quiz

Which end of a channel sends a message?

Right! tx sends ("transmit") and rx receives. πŸ“¨

You learned… A channel lets threads pass notes. tx.send(x) sends and rx.recv() receives. Next up: sharing the same thing safely with Sharing Safely (Mutex)! πŸ”