Skip to content

Commit 0676d21

Browse files
committed
Add code to demonstrate Sending Messages between Threads
1 parent e3b34d0 commit 0676d21

File tree

2 files changed

+63
-4
lines changed

2 files changed

+63
-4
lines changed

documentation2/B09-Thread.md

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -335,3 +335,51 @@ We are telling Rust that the main thread won't use the `message` variable anymor
335335
Note that moving a value into a thread can be useful for parallelism, but it can also be a source of bugs if not used carefully.
336336
337337
____
338+
339+
## Sending Messages between Threads in Rust
340+
341+
In Rust, threads can communicate with each other by sending messages through channels. A channel is a way to send values between threads, and it can be used to synchronize communication and avoid data races.
342+
343+
We use the `channel()` function in the `std::sync::mspsc` module to create a channel in Rust.
344+
345+
Let's take a look at how we can use channels to communicate between threads.
346+
347+
```rust
348+
use std::sync::mpsc;
349+
use std::thread;
350+
351+
fn main() {
352+
// main thread starts here
353+
// create a new channel
354+
let (sender, receiver) = mpsc::channel();
355+
356+
// spawn a new thread
357+
let handle = thread::spawn(move || {
358+
// receive message from channel
359+
let message = receiver.recv().unwrap();
360+
361+
println!("Received message: {}", message);
362+
});
363+
364+
let message = String::from("Hello, World!");
365+
// send message to channel
366+
sender.send(message).unwrap();
367+
368+
// wait for spawned thread to finish
369+
handle.join().unwrap();
370+
}
371+
```
372+
373+
```bash
374+
cargo build
375+
```
376+
377+
```bash
378+
cargo run
379+
```
380+
381+
### Output
382+
383+
```bash
384+
Received message: Hello, World!
385+
```
Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,23 @@
1+
use std::sync::mpsc;
12
use std::thread;
23

34
fn main() {
4-
let message = String::from("Hello, World!");
5+
// main thread starts here
6+
// create a new channel
7+
let (sender, receiver) = mpsc::channel();
8+
9+
// spawn a new thread
10+
let handle = thread::spawn(move || {
11+
// receive message from channel
12+
let message = receiver.recv().unwrap();
513

6-
// using the message variable without a move
7-
let handle = thread::spawn(|| {
8-
println!("{}", message);
14+
println!("Received message: {}", message);
915
});
1016

17+
let message = String::from("Hello, World!");
18+
// send message to channel
19+
sender.send(message).unwrap();
20+
21+
// wait for spawned thread to finish
1122
handle.join().unwrap();
1223
}

0 commit comments

Comments
 (0)