[Rust] Thread 5: Message passing by using channel

A channel has two halves: a transmitter and a receiver. The transmitter half is the upstream location where you put rubber ducks into the river, and the receiver half is where the rubber duck ends up downstream. One part of your code calls methods on the transmitter with the data you want to send, and another part checks the receiving end for arriving messages. A channel is said to be closed if either the transmitter or receiver half is dropped.

 

A simple channel creation, code won't do anything, cannot compile yet:

use std::sync::mpsc;

fn main() {
    let (tx, rx) = mpsc::channel();
}

We create a new channel using the mpsc::channel function; mpsc stands for multiple producer, single consumer.

The mpsc::channel function returns a tuple, the first element of which is the sending end--the transmitter--and the second element is the receiving end--the receiver. The abbreviations tx and rx are traditionally used in many fields for transmitter and receiver respectively, so we name our variables as such to indicate each end.

 

Put txinto a child thread to talk to main thread:

use std::sync::mpsc;
use std::thread;

fn main() {
    let (tx, rx) = mpsc::channel();

    thread::spawn(move || {
        let val = String::from("hi");
        tx.send(val).unwrap();
    });
}

 

Now we add rxto receive the data in main thread:

use std::sync::mpsc;
use std::thread;

fn main() {
    let (tx, rx) = mpsc::channel();

    thread::spawn(move || {
        let val = String::from("hi");
        tx.send(val).unwrap();
    });

    let received = rx.recv().unwrap();
    println!("Got: {}", received);
}

The receiver has two useful methods: recv and try_recv. We’re using recv, short for receive, which will block the main thread’s execution and wait until a value is sent down the channel. Once a value is sent, recv will return it in a Result<T, E>. When the transmitter closes, recv will return an error to signal that no more values will be coming.

The try_recv method doesn’t block, but will instead return a Result<T, E> immediately: an Ok value holding a message if one is available and an Err value if there aren’t any messages this time. Using try_recv is useful if this thread has other work to do while waiting for messages: we could write a loop that calls try_recv every so often, handles a message if one is available, and otherwise does other work for a little while until checking again.

 

When we run the code, we will be able to receive the message:

Got: hi

 

posted @   Zhentiw  阅读(3)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2021-03-12 [AWS Design Cost-Optimized Architectures] 4.1 Identify cost-effective storage solutions
2019-03-12 [Algorithm] Tree: Lowest Common Ancestor
2019-03-12 [NPM] Execute Code from a Remote GitHub Branch with npx
2019-03-12 [NPM] Execute npx commands with $npm_ Environment Variables
2019-03-12 [NPM] Use npx to run commands with different Node.js versions
2019-03-12 [Node.js] Gzip + crypto in stream
2019-03-12 [Node.js] Stream all things!
点击右上角即可分享
微信分享提示