Skip to content

Commit 806811b

Browse files
committed
Add notes to close out Thread Chapter
1 parent 0676d21 commit 806811b

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

documentation2/B09-Thread.md

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -383,3 +383,41 @@ cargo run
383383
```bash
384384
Received message: Hello, World!
385385
```
386+
387+
Here, we create a channel using the `channel()` function. The `std::sync::mpsc` module provides **multiple-producer, single-consumer** (mspc) channels that can be used to send values between threads.
388+
389+
```bash
390+
// create a new channel
391+
let (sender, receiver) = mpsc::channel();
392+
```
393+
394+
The `sender` and `receiver` variables represent the two endpoints of the channel. The sender endpoint is used to send messages, while the receiver endpoint is used to receive messages.
395+
396+
```bash
397+
// spawn a new thread
398+
let handle = thread::spawn(move || {
399+
// receive message from channel
400+
let message = receiver.recv().unwrap();
401+
402+
println!("Received message: {}", message);
403+
});
404+
```
405+
406+
We also create a spawned thread using the `thread::spawn()` function. The closure passed to the function receives a message using the `receiver.recv()` method.
407+
408+
The `recv()` method blocks until a message is received on the channel, and it returns a `Result` indicating whether a message was received or an error occurred.
409+
410+
```bash
411+
let message = String::from("Hello, World!");
412+
// send message to channel
413+
sender.send(message).unwrap();
414+
```
415+
416+
In the main thread, a `message` is created and sent using the `sender.send()` method. The `send()` method returns a `Result` indicating whether the message was successfully sent or an error occurred.
417+
418+
```bash
419+
// wait for spawned thread to finish
420+
handle.join().unwrap();
421+
```
422+
423+
Finally, the `join()` method is called on the handle to wait for the spawned thread to finish before the program exits.

0 commit comments

Comments
 (0)