Rust std::thread::spawn(move) 的作用

rust 复制代码
    for ip in ip_list {
        let s1 = sem.clone();
        let d1 = done_snd.clone();
        let o1 = opt.clone();
        // async move   move 
        std::thread::spawn(move || {
            let rt = tokio::runtime::Runtime::new().unwrap();
            rt.block_on(async {
                let sem = s1.acquire_owned().await.unwrap();
                info!("try to path {ip}");
                match process_host_with_retry(&o1, &ip).await {
                    Ok(_) => d1.send(WriteMsg::Ok(ip.to_string())).await.unwrap(),
                    Err(e) => {
                        warn!("patch {ip} failed, {e}");
                        d1.send(WriteMsg::Err(ip.to_string())).await.unwrap()
                    }
                }

                drop(sem);
            });
        });
    } 

围观大佬于写代码。出现这个问题。写的时候带了 async 就无法执行了。搜索了一下:

原因:

async 关键字把代码块变成了一个 Future ,它不会在创建时立即执行,而是要等到被 poll/await 才会真正跑起来;而 std::thread::spawn 期待的是一个立刻就会在新线程里 同步执行 的函数体 (FnOnce() -> T)。
一句话 :把 async 放到 move 前后,只是生成了一个 future;如果你不在同一个线程里 await/block_on 它,逻辑就永远不会被调度

去掉 async,闭包又变回同步函数体,线程启动后就直接执行!!!

关键点回顾

  1. async 块 ≠ 立即执行 :它只是"构建"一个状态机,真正运行发生在 .await/poll

  2. std::thread::spawn 只能执行同步闭包------要么在闭包里 block_on,要么别用它。

  3. Tokio runtime 已经能并发调度 future,通常不需要再额外开 OS 线程。

相关推荐
SelectDB9 分钟前
Apache Doris AI 能力揭秘(三):AI_AGG 与 EMBED 函数深度解析
数据库·后端·apache
CodeCraft Studio10 分钟前
Excel处理控件Aspose.Cells教程:使用Python从Excel工作表中删除数据透视表
开发语言·python·excel·aspose·aspose.cells·数据透视表
清晰-简洁18 分钟前
Spring Boot 单元测试按需加载
spring boot·后端·单元测试
linuxxx11020 分钟前
高考志愿填报辅助系统
redis·后端·python·mysql·ai·django·高考
学IT的周星星25 分钟前
SpringMVC请求参数的绑定
java·开发语言
普通网友31 分钟前
高性能TCP服务器设计
开发语言·c++·算法
MegatronKing35 分钟前
Reqable 3.0版本云同步的实践过程
前端·后端·测试
普通网友37 分钟前
C++与硬件交互编程
开发语言·c++·算法
快手技术40 分钟前
闪耀NeurIPS 2025!快手13篇论文入选,Spotlight 成果跻身前三!
前端·后端
Starduster41 分钟前
一次数据库权限小改动,如何拖垮半个互联网?——Cloudflare 2025-11-18 大故障复盘
数据库·后端·架构