gpt4 book ai didi

multithreading - 为什么当子程序很昂贵时多线程执行不起作用?

转载 作者:行者123 更新时间:2023-11-29 08:26:06 25 4
gpt4 key购买 nike

<分区>

此程序随机打印索引号,例如 1, 4, 2, 3, 100 ....

use std::thread;

fn main() {
for x in 0..100 {
print!("{}: {:?} ", x, child.join());
}
}

但是,一旦我添加了 ping() 函数,它执行的不是控制台输出,它就不再并发执行,而只是迭代 ping() 函数.

extern crate serde;
extern crate serde_derive;
extern crate reqwest;

use reqwest::Client;
use std::thread;
use std::process::Command;

fn main() {
for x in 0..100 {
let child = thread::spawn(move || {
ping(x);
});
print!("{}: {:?} ", x, child.join());
}
}

fn ping(x: i32) {
let output = if cfg!(target_os = "windows") {
Command::new("cmd")
.args(&["/C", "echo hello"])
.output()
.expect("failed to execute process")
} else {
Command::new("sh")
.arg("-c")
.arg("https://keisugano.blogspot.com/")
.output()
.expect("failed to execute process")
};
println!("{:?}", output);
}

此问题的根本原因是什么,我该如何解决?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com