[Rust] Intro Thread: 1. Thread with spawn

We use spawnto create a new thread:

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));
    }
}

Note that when the main thread of a Rust program completes, all spawned threads are shut down, whether or not they have finished running. The output from this program might be a little different every time, but it will look similar to the following:

hi number 1 from the main thread!
hi number 1 from the spawned thread!
hi number 2 from the main thread!
hi number 2 from the spawned thread!
hi number 3 from the main thread!
hi number 3 from the spawned thread!
hi number 4 from the main thread!
hi number 4 from the spawned thread!
hi number 5 from the spawned thread!

 

The main thread will always run first, no matter the code order. That's why you see output from main thread first.

If you run this code and only see output from the main thread, or don’t see any overlap, try increasing the numbers in the ranges to create more opportunities for the operating system to switch between the threads.

 

Notice that, we list 1..10for main thread, but it only log until 5, this is due to main thread shut down everything. Will continue with solution to resolve this issue in next blog about joinhandler

posted @   Zhentiw  阅读(8)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2021-03-08 [CSS] Choose between Grid layout and flexbox
2020-03-08 [React] Avoiding state flickers
2019-03-08 [Node.js] Load balancing a Http server
2019-03-08 [Node.js] Child Process with fork() to handle heavy calculation process
2019-03-08 [Algorithm] Write your own Math.pow function in Javascript, using Recursive approach
2019-03-08 [Functional Programming] Fst & Snd, Code interview question
2019-03-08 [React GraphQL] Pass Parameters to urql's useQuery React Hook
点击右上角即可分享
微信分享提示