登录
首页 >  Golang >  Go问答

Rust和Go的并发代码是类似的吗?

来源:stackoverflow

时间:2024-02-07 10:09:16 284浏览 收藏

在IT行业这个发展更新速度很快的行业,只有不停止的学习,才不会被行业所淘汰。如果你是Golang学习者,那么本文《Rust和Go的并发代码是类似的吗?》就很适合你!本篇内容主要包括##content_title##,希望对大家的知识积累有所帮助,助力实战开发!

问题内容

我一直致力于在 rust 中实现多线程功能。我正在尝试翻译用 go 编写的代码,该代码在迭代时更新地图的值并创建一个新线程。 (简化代码)

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)
}

到目前为止我尝试过这样

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();
}

正确答案


我创建了一个类似于等待组的处理程序向量,并将每个线程推送到那里。然后,我迭代每个句柄和 .unwrap() 以确保它完成。

let mut handles: Vec> = Vec::new();

    for (key, value) in my_map.iter_mut() {
        handles.push(thread::spawn(move || {
            let cmd = format!("some command");
            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 = match proc {
                Ok(proc) => proc,
                Err(e) => {
                    panic!("Failed to create process: {:?}", e)
                }
            };

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

            *value = "I will update value with something new";
        }));
   }
    for handle in handles {
        handle.join().unwrap(); // This won't block other threads, but it will make sure it can unwrap every thread before it continues. In other words, this only runs as long as your longest running thread.
    }

理论要掌握,实操不能落!以上关于《Rust和Go的并发代码是类似的吗?》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>