π¨
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)! π