You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Go并发更新Map的代码转换为等价Rust实现?

Rust多线程更新HashMap问题

我在实现Rust多线程功能时遇到了困难,正尝试将自己用Go编写的、在迭代过程中开启新线程更新Map值的代码转换为Rust代码(以下为简化版代码):

my_map := make(map[string]string)
var wg sync.WaitGroup
wg.Add(len(my_map ))

for key := range my_map {
    go func(key string) {
        defer wg.Done()
        stdout, _ := exec.Command(key, "some command").Output()

        lock.Lock()
        defer lock.Unlock()
        my_map[key] = "updating map value while iterating"  // eg stdout
    }(key)
}

我目前尝试的Rust代码如下:

let mut my_map = HashMap::new();

...

for (key, value) in my_map.iter_mut() {
    // Should update map value, tried with crossbeam_utils:thread;

    thread::scope(|s| {
        s.spawn(|_| {
            let cmd = format!("some command {key}");  // will borrow key
            let cmd: Vec<&str> = cmd.as_str().split(" ").map(|s| s).collect();

            let proc = Popen::create(
                &cmd,
                PopenConfig {
                    stdout: Redirection::Pipe,
                    stdin: Redirection::None,
                    stderr: Redirection::None,
                    ..Default::default()
                },
            );

            let mut proc = proc.expect("Failed to create process.");

            let (out, _) = proc.communicate(None).unwrap();
            let stdout = out.unwrap();

            *value = "I will update value with something new";
        });
    })
    .unwrap();
}

内容的提问来源于stack exchange,提问作者alfex4936

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 15:45:57