首页 > 其他分享 >[Rust] Thread 6: Using channel to receive multi data

[Rust] Thread 6: Using channel to receive multi data

时间:2024-03-12 22:22:35浏览次数:23  
标签:multi Thread thread receive use Got main channel String

use std::sync::mpsc;
use std::thread;
use std::time::Duration;

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

    thread::spawn(move || {
        let vals = vec![
            String::from("hi"),
            String::from("from"),
            String::from("the"),
            String::from("thread"),
        ];

        for val in vals {
            tx.send(val).unwrap();
            thread::sleep(Duration::from_secs(1));
        }
    });

    for received in rx {
        println!("Got: {}", received);
    }
}

This time, the spawned thread has a vector of strings that we want to send to the main thread. We iterate over them, sending each individually, and pause between each by calling the thread::sleep function with a Duration value of 1 second.

In the main thread, we’re not calling the recv function explicitly anymore: instead, we’re treating rx as an iterator. For each value received, we’re printing it. When the channel is closed, iteration will end.

Output:

Got: hi
Got: from
Got: the
Got: thread

Because we don’t have any code that pauses or delays in the for loop in the main thread, we can tell that the main thread is waiting to receive values from the spawned thread.

标签:multi,Thread,thread,receive,use,Got,main,channel,String
From: https://www.cnblogs.com/Answer1215/p/18069490

相关文章

  • D. Divide by three, multiply by two
    https://codeforces.com/contest/977/problem/Dvoidsolve(){intn;cin>>n;vector<pair<int,longlong>>a(n);for(auto&[x,y]:a){cin>>y;x=0;longlongtemp=y;while(......
  • JUC源码讲解:逐步解析 Thread.start() 源码
    JUC源码讲解:逐步解析Thread.start()源码抛出问题当newThread()时,线程会进入NEW状态,如果我们想要使用线程,就需要调用start()方法,那么,在使用star()时发生了什么?有什么需要注意的?线程是怎么一步步被创建的?跟着我一起分析源码吧!阅读源码为了方便讲解,我先把源码贴出来,然......
  • JUC源码讲解:逐步解析 Thread.init() 源码
    #JUC源码讲解:逐步解析Thread.init()源码抛出问题我们在newThread()时,init()方法便会自动调用,用来创建这个线程。那么,创建线程时都发生了什么事?子线程与父线程有何关系?线程是怎么创建的?juc怎么选择ThreadGroup?让我们从源码中寻找答案吧!查看源码privatevoidini......
  • Practical Learned Lossless JPEG Recompression with Multi-Level Cross-Channel Ent
    目录简介模型DCTCoefficientsRearrangement将系数重排Cross-ColorEntropyModelMatrixContextModelMulti-LevelCross-ChannelEntropyModel创新点实验设置训练数据集:测试数据集:训练细节:结果简介JPEG是一种非常流行的压缩方法,然而最近关于图像压缩的研究主要集中在未压......
  • 【PR】UC-NERF: NEURAL RADIANCE FIELD FOR UNDERCALIBRATED MULTI-VIEW CAMERAS IN A
    【简介】这篇文章的作者来自中科大、北大武汉人工智能研究院、大疆和上海科大,投稿到了ICLR2024会议,已接收。UC,表示undercalibrated,意味着标定不准。本文提出UC-NeRF用于解决标定不够好的多相机配置的新视角合成方法。首先,作者提出一种基于层的颜色校正方法,以纠正不同图像区域......
  • [Rust] Thread 3: move keyword to resolve borrowing problem for closure
    Weofteruse movewithclosurespassedto thread::spawnbecasetheclosurewillthentakeownershipofthevaluesitusesfromtheenvironment,thustransferringowershopofthosevaluesfromonethreadtoanother. Thefollowingcodewon'twork:use......
  • OpenMP-threadprivate
    threadprivate是OpenMP中的一个指令,用于在多线程环境中为每个线程创建私有变量。通常情况下,OpenMP中的变量默认是共享的,也就是说所有线程都可以访问同一个变量的同一份副本。然而,在某些情况下,需要为每个线程创建独立的变量副本,以避免并发访问问题。threadprivate指令允许程序员将......
  • [Rust] Thread 2: Waiting all thread to finish using join handler
    Codefrompreviousblog:usestd::thread;usestd::time::Duration;fnmain(){thread::spawn(||{foriin1..10{println!("hinumber{}fromthespawnedthread!",i);thread::sleep(Duration::from_millis(1))......
  • [Rust] Intro Thread: 1. Thread with spawn
    Weuse spawntocreateanewthread:usestd::thread;usestd::time::Duration;fnmain(){thread::spawn(||{foriin1..10{println!("hinumber{}fromthespawnedthread!",i);thread::sleep(Duration::from......
  • 并发编程Thread的常用API有哪些?
    引言在JDK17(或以上版本)中,Thread类提供了一组常用的API,用于管理线程的创建、启动、暂停、恢复和销毁等操作。本文从api、源码、编程示例等方面详细说明Thread常用函数的使用和注意事项。线程sleep使当前正在执行的线程暂停(挂起)指定的毫秒数。但受系统计时器和调度程序的精度......