首页 > 其他分享 >[Rust] Thread 2: Waiting all thread to finish using join handler

[Rust] Thread 2: Waiting all thread to finish using join handler

时间:2024-03-08 20:57:47浏览次数:27  
标签:finish join Thread thread number hi Duration main spawned

Code from previous blog:

use std::thread;
use std::time::Duration;

fn main() {
    thread::spawn(|| {
        for i in 1..10 {
            println!("hi number {} from the spawned thread!", i);
            thread::sleep(Duration::from_millis(1));
        }
    });

    for i in 1..5 {
        println!("hi number {} from the main thread!", i);
        thread::sleep(Duration::from_millis(1));
    }
}

Code stops the spawned thread prematurely most of the time due to the main thread ending.

 

To fix that we can use join:

use std::thread;
use std::time::Duration;

fn main() {
    let handle = thread::spawn(|| {
        for i in 1..10 {
            println!("hi number {} from the spawned thread!", i);
            thread::sleep(Duration::from_millis(1));
        }
    });

    for i in 1..5 {
        println!("hi number {} from the main thread!", i);
        thread::sleep(Duration::from_millis(1));
    }

    handle.join().unwrap();
}

 

Calling join on the handle blocks the thread currently running until the thread represented by the handle terminates. Blocking a thread means that thread is prevented from performing work or exiting. Because we’ve put the call to join after the main thread’s for loop, running Listing 16-2 should produce output similar to this:

hi number 1 from the main thread!
hi number 2 from the main thread!
hi number 1 from the spawned thread!
hi number 3 from the main thread!
hi number 2 from the spawned thread!
hi number 4 from the main thread!
hi number 3 from the spawned thread!
hi number 4 from the spawned thread!
hi number 5 from the spawned thread!
hi number 6 from the spawned thread!
hi number 7 from the spawned thread!
hi number 8 from the spawned thread!
hi number 9 from the spawned thread!

 

Notice here we call handle.join().unwrap();at the end of main function. This is important, let's see what if we do as such:

fn main() {
    let handle = thread::spawn(|| {
        for i in 1..10 {
            println!("hi number {} from the spawned thread!", i);
            thread::sleep(Duration::from_millis(1));
        }
    });

    handle.join().unwrap(); // move it here

    for i in 1..5 {
        println!("hi number {} from the main thread!", i);
        thread::sleep(Duration::from_millis(1));
    }
}

The output:

hi number 1 from the spawned thread!
hi number 2 from the spawned thread!
hi number 3 from the spawned thread!
hi number 4 from the spawned thread!
hi number 5 from the spawned thread!
hi number 6 from the spawned thread!
hi number 7 from the spawned thread!
hi number 8 from the spawned thread!
hi number 9 from the spawned thread!
hi number 1 from the main thread!
hi number 2 from the main thread!
hi number 3 from the main thread!
hi number 4 from the main thread!

Now it wait the spawned thread finish before run the main thread. It might cause unexpected behavior.

标签:finish,join,Thread,thread,number,hi,Duration,main,spawned
From: https://www.cnblogs.com/Answer1215/p/18061835

相关文章

  • [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......
  • gorm 中left join的使用
    使用mysql语句执行时可以执行成功,但是使用go语言编程保存到struct中时出现问题。代码如下:sflog.Debug("QueryByTaskId",id)  typeDatastruct{    TaskId     int64 `json:"taskId"`    VehicleName  string `json:"vehicleNa......
  • Rails中的includes和joins的区别与用法
    includes和joins的不同当includes和joins的时候最重要的概念就是他们有他们的典型用例。includes使用贪婪加载(eagerloading)而joins使用懒加载(lazyloading),两者都非常有用,但是也都很容易被滥用导致程序性能降低或过度使用。如果我们看一眼rubyonrails文档,描述includes最重......
  • 并发编程Thread的常用API有哪些?
    引言在JDK17(或以上版本)中,Thread类提供了一组常用的API,用于管理线程的创建、启动、暂停、恢复和销毁等操作。本文从api、源码、编程示例等方面详细说明Thread常用函数的使用和注意事项。线程sleep使当前正在执行的线程暂停(挂起)指定的毫秒数。但受系统计时器和调度程序的精度......
  • RT-THREAD的STM32F4系列移植
    RT-Thread:RT-Thread,全称是RealTime-Thread,顾名思义,它是一个嵌入式实时多线程操作系统,基本属性之一是支持多任务,但允许多个任务同时运行并不意味着处理器在同一时刻真的执行了多个任务。事实上,一个处理器核心在某一时刻只能运行一个任务,由于每次对一个任务的执行时间很短、任务......
  • TransmittableThreadLocal 的反复与纠缠
    TransmittableThreadLocal相信很多人用过,一个在多线程情况下共享线程上下文的利器名字好长,以下简称ttl本文以两年前一个真实项目开发遇到的问题,从源码的角度分析并解决环境itemversionjava8springboot2.2.2.RELEASEttl2.11.4代码如下,主线程并行启复......
  • MySQL JOIN 的执行过程
    对于MySQL的JOIN,不知道大家有没有去想过他的执行流程,亦或有没有怀疑过自己的理解;如果大家不知道怎么检验,可以试着回答如下的问题。 驱动表的选择:MySQL会如何选择驱动表,按从左至右的顺序选择第一个? 多表连接的顺序 假设我们有3张表:A、B、C,和如下SQL --伪SQL,......
  • springboot3+vue3(四.2)ThreadLocal优化
    解决痛点:我们在拦截器内已经获取并解析了一遍token数据,如图:然后在获取当前登录用户详细信息时又做了一遍同样的操作,如图:后续如果说需要用到当前登录用户的信息时都要带上token参数,这样是很冗余的。这时就会用到ThreadLocal来进行优化处理。 ThreadLocal工具类/***......
  • C++ Qt开发:运用QThread多线程组件
    Qt是一个跨平台C++图形界面开发库,利用Qt可以快速开发跨平台窗体应用程序,在Qt中我们可以通过拖拽的方式将不同组件放到指定的位置,实现图形化开发极大的方便了开发效率,本章将重点介绍如何运用QThread组件实现多线程功能。多线程技术在程序开发中尤为常用,Qt框架中提供了QThread库来......
  • Java 切入点 JoinPoint的使用,用于拦截方法,与自定义注解
    这里的代码案例是外卖系统中,用于统一修改新增和更新内容中的更新时间与更新人内容,根据具体情况,在使用时进行自定义修改就行了第一部分是annotation的,因为是为了自动填充数据准备,所以创建annotation包后,在其中创建了AutoFill的注解类型/***自定义注解,用于标识某个方法需要用......