Rust programming video tutorial (Advanced) – 017_ 1 messaging 1


Video address

Headline address:…
Station B address:

Source address

GitHub address:…

Explanation content

1. One of the main tools for implementing message passing concurrency in rust is the channel. The channel consists of two parts, one is the sender and the other is the receiver. The sender is used to send messages and the receiver is used to receive messages. When either sender or receiver is discarded, the channel can be considered closed.

2. Channel introduction
(1) Create channels through MPSC:: channel. MPSC is multiple producers and a single consumer;
(2) Create channels through SPMC:: channel. SPMC is a producer and multiple consumers;
(3) After the channel is created, the sender and consumer are returned, for example:

let (tx, rx) = mpsc::channel();
let (tx, rx) = spmc::channel();

3. Example

use std::thread; 
use std::sync::mpsc; 
fn main() { 
    let (tx, rx) = mpsc::channel();// Return sender and receiver
    thread::spawn(move || { 
        let val = String::from("hi");
        tx.send(val).unwrap(); // Send via channel using sender
    let received = rx.recv().unwrap();// Use the receiver to receive through the channel 
    println!("Got: {}", received); 

Knowledge points:
(1) The sender’s send method returns a result < T, E > type. If the receiver has been discarded, there will be no target to send the value, so the sending operation will return an error;
(2) The receiver’s recv method also returns the result < T, E > type. When the channel sender is closed, an error value will be returned, indicating that the new value will not come again;
(3) Try can also be used for reception_ Recv method, the recv method will block until the message arrives, and try_ Recv will not block. It will return immediately. The OK value indicates that there is available information, while err indicates that there is no information at this time.

This work adoptsCC agreement, reprint must indicate the author and the link to this article

Linghu rushed

Recommended Today

SQL exercise 20 – Modeling & Reporting

This blog is used to review and sort out the common topic modeling architecture, analysis oriented architecture and integration topic reports in data warehouse. I have uploaded these reports to GitHub. If you are interested, you can have a lookAddress: recorded a relatively complete development process in my hexo blog deployed on GitHub. You can […]