首页 > 其他分享 >[Rust] Thread 5: Message passing by using channel

[Rust] Thread 5: Message passing by using channel

时间:2024-03-12 22:25:33浏览次数:18  
标签:transmitter mpsc Thread thread channel using tx recv Rust

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

 

标签:transmitter,mpsc,Thread,thread,channel,using,tx,recv,Rust
From: https://www.cnblogs.com/Answer1215/p/18069480

相关文章

  • [Rust] Thread 6: Using channel to receive multi data
    usestd::sync::mpsc;usestd::thread;usestd::time::Duration;fnmain(){let(tx,rx)=mpsc::channel();thread::spawn(move||{letvals=vec![String::from("hi"),String::from("from"),......
  • JUC源码讲解:逐步解析 Thread.start() 源码
    JUC源码讲解:逐步解析Thread.start()源码抛出问题当newThread()时,线程会进入NEW状态,如果我们想要使用线程,就需要调用start()方法,那么,在使用star()时发生了什么?有什么需要注意的?线程是怎么一步步被创建的?跟着我一起分析源码吧!阅读源码为了方便讲解,我先把源码贴出来,然......
  • JUC源码讲解:逐步解析 Thread.init() 源码
    #JUC源码讲解:逐步解析Thread.init()源码抛出问题我们在newThread()时,init()方法便会自动调用,用来创建这个线程。那么,创建线程时都发生了什么事?子线程与父线程有何关系?线程是怎么创建的?juc怎么选择ThreadGroup?让我们从源码中寻找答案吧!查看源码privatevoidini......
  • [Rust] Thread 3: move keyword to resolve borrowing problem for closure
    Weofteruse movewithclosurespassedto thread::spawnbecasetheclosurewillthentakeownershipofthevaluesitusesfromtheenvironment,thustransferringowershopofthosevaluesfromonethreadtoanother. Thefollowingcodewon'twork:use......
  • [Learn]Build a Business Application Using CAP for Node.js
    https://developers.sap.com/mission.cp-starter-extensions-cap.html1、使用VSCode创建服务https://developers.sap.com/tutorials/cp-apm-nodejs-create-service.html 通过使用SAPCloud应用程序编程模型(CAP)并在本地环境中进行开发,使用CoreData&Services(CDS)、N......
  • rust 安装及更新
    安装下载https://static.rust-lang.org/rustup/dist/x86_64-pc-windows-msvc/rustup-init.exe设置Rustup镜像添加path环境变量RUSTUP_DIST_SERVER="https://rsproxy.cn"RUSTUP_UPDATE_ROOT="https://rsproxy.cn/rustup"设置crates.io镜像,修改配置~/.cargo/con......
  • Rust-入门-01
    Rust语言有哪些特性?建议一:从整体出发,不要让自己陷入到细节中去建议二:抛弃一次性学会的念头语言架构所有权系统编程范式语言架构类型系统内存管理Rust语言设计哲学是什么?Rust社区和生态如何?参考1......
  • .Net Core 的 using 作用
    //using的使用//1.引用命名空间usingnamespace//2.自动释放资源执行结束自动调用IDispose接口释放资源//using(varcontext=newtestController()){}//3.起一个别名//如果两个类中有一个相同的方法,使用别名的方式进行运行避免冲突//usings1=same1......
  • OpenMP-threadprivate
    threadprivate是OpenMP中的一个指令,用于在多线程环境中为每个线程创建私有变量。通常情况下,OpenMP中的变量默认是共享的,也就是说所有线程都可以访问同一个变量的同一份副本。然而,在某些情况下,需要为每个线程创建独立的变量副本,以避免并发访问问题。threadprivate指令允许程序员将......
  • What is Rust's turbofish
    Haveyoueverheardaboutthe“turbofish”?ItisthatpieceofRustsyntaxthatlookslike ::<SomeType>.InthispostIwilldescribewhatitdoesandhowtouseit.Firstof,ifyouweretowritesomethinglikethis:fnmain(){letnumbers:Ve......