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

相关推荐
devilnumber20 小时前
Java 递归算法 详解 + 核心要点 + 实战运用 + 避坑指南
java·开发语言·算法
独泪了无痕20 小时前
MyBatis魔法堂:结果集映射
后端·mybatis
copyer_xyf21 小时前
LangChain 调用 LLM
后端·python·agent
copyer_xyf21 小时前
Prompt 组织管理
后端·python·agent
asdfg125896321 小时前
JavaBean是什么?怎么理解?有什么用途?
java·开发语言
dsyyyyy110121 小时前
JavaScript变量
开发语言·javascript·ecmascript
z落落1 天前
C#WinForm 窗体切换与窗体传值(登录跳转案例)+WinForm 窗体传值(从上往下传、从下往上传)
开发语言·windows·c#
allway21 天前
How to Echo Multiline to a File in Bash [3 Methods]
开发语言·chrome·bash
weixin_462446231 天前
手把手教你用 Bash 脚本自动更新 /etc/hosts —— 自动绑定网卡 IP 与节点名
开发语言·tcp/ip·bash
一个梦醒了1 天前
安装git bash选项推荐
开发语言·git·bash