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

相关推荐
卷无止境40 分钟前
Python能做嵌入式开发吗?一份写给动手派的生态与硬件全景图
后端·python
OPEN-F5 小时前
C++进阶教程:继承与多态
开发语言·c++
Sherotree7 小时前
Google Antigravity——Agent 被提到主界面
前端·ide·后端·edge浏览器
2601_962056237 小时前
Spring Boot 入门 与 无法解析符号 springframework 的解决
java·spring boot·后端
luj_17687 小时前
大律师考核应重能力与科技素养
c语言·开发语言·c++·经验分享·算法
你驴我8 小时前
WhatsApp 多账号场景下的会话归档与历史消息检索优化实践
后端·python
学长毕业设计8 小时前
基于SpringBoot的瑜伽馆网站的设计与实现(源码+文档+讲解视频)
java·spring boot·后端
leonkay8 小时前
C# 特性(Attribute)——【1】基础讲解
开发语言·青少年编程·面试·c#·.net·个人开发
harmful_sheep8 小时前
java group by常见用法
java·开发语言·python
SKH.8 小时前
Linux软件编程(6)线程间通信
java·开发语言·数据库