You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: documentation2/B09-Thread.md
+38Lines changed: 38 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -383,3 +383,41 @@ cargo run
383
383
```bash
384
384
Received message: Hello, World!
385
385
```
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