[Rust] Intro Thread: 1. Thread with spawn
We use spawn
to 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..10
for 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 join
handler
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源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