【发布时间】:2022-07-21 17:44:00
【问题描述】:
我有一些异步功能
async fn get_player(name: String, i: Instant) -> Option<Player> {
// some code here that returns a player structs
}
在我的主函数中,我想在一个循环中同时运行上述函数,这个函数大约需要 1 秒才能完成,我需要运行它至少 50 次,因此我想让它同时运行这个函数 50 次.在我的主函数中,我有一个lazy_static 自定义Client 结构,不应多次创建。
主要功能
#[tokio::main]
async fn main() {
client.init().await;
println!("start");
for i in 0..10 {
println!("{}", i);
let now = Instant::now();
tokio::spawn(async move {
client.get_player("jay".to_string(), now).await;
});
}
loop {}
}
我传递即时的原因是因为在我的 get_player 函数中我有一个 println!() 只打印执行时间。
上面的main方法每个函数调用大约需要500ms,而下面的代码只需要100ms。
#[tokio::main]
async fn maain(){
client.init().await;
for i in 0..10 {
let now = Instant::now();
client.get_player("jay".to_string(), now).await.expect("panic");
}
}
但是这个函数仍然是同步代码,我如何真正并发运行异步函数而不需要时间成本?
- 为了更好地理解 am after 是一个与此类似的实现(它在 java 中顺便说一句),
CompleteableFuture.thenAccept(x -> x.SayHello(););
或者在 Js 中它类似于 .then 在异步函数之后。
rust 中有没有类似的实现?
【问题讨论】:
-
每个函数调用的 500 毫秒——这些是同时发生的还是连续发生的?一个函数调用能否在另一个函数的 500 毫秒内启动?
-
如果你想要并发,我不认为
async是要走的路。 Here is a description of what the differences between these approaches are。在 Rust 中,除非主动轮询,否则期货不会取得进展。tokio(或其他异步运行时)为您抽象和管理它,所以您能做的最好的事情就是将未来存储在一个变量中,以供以后使用。对于真正的并发,你应该使用线程。 -
@PitaJ 并行意味着并发,但您可以使用上下文切换在单个处理器上运行多个(并发)执行线程,而不是并行运行。
-
这能回答你的问题吗? tokio join multiple tasks in rust
-
this playground 有帮助吗?是否需要
spawn将取决于您是否需要默认多线程运行时的并行性。
标签: rust rust-tokio rust-async-std