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 线程。

相关推荐
Moment几秒前
如果你在做 RAG,可能会需要 pdf-inspector
前端·后端·面试
Wx-bishekaifayuan14 分钟前
django医院营收信息预测系统49414-计算机课程设计、毕业设计
spring boot·后端·python·django·课程设计·express·旅游
Wx-bishekaifayuan15 分钟前
springboot会议室预约管理系统42030-计算机课程设计、毕业设计
spring boot·后端·python·django·课程设计·express·旅游
AINative软件工程22 分钟前
LLM 输出 Guardrail 工程实践:5 层防护栏让 AI 生成的内容不会炸掉生产
后端·llm·ai编程
IT_陈寒44 分钟前
Vite热更新失效?你可能漏了这个配置项
前端·人工智能·后端
Wx-bishekaifayuan1 小时前
springboot生活商城系统21035-计算机课程设计、毕业设计
spring boot·后端·python·spring·elasticsearch·golang·课程设计
云浪1 小时前
通过 Goroutine 搞懂 Go 并发与常见的 9 个坑
后端·go
Wx-bishekaifayuan1 小时前
springboot贵州旅游系统55916-计算机课程设计、毕业设计
spring boot·后端·python·django·课程设计·express·旅游
Fruit_Caller1 小时前
static
开发语言·c++
mldong1 小时前
事务不归引擎管:ITransactionTemplate,聚合一致性的最后一块拼图
后端·架构