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

确认Tokio异步示例代码是否为顺序执行的技术问询

关于Tokio异步代码执行逻辑的疑问

以下是Tokio入门教程中的一段代码:

use mini_redis::{client, Result};

#[tokio::main]
async fn main() -> Result<()> {
    // Open a connection to the mini-redis address.
    let mut client = client::connect("127.0.0.1:6379").await?;

    // Set the key "hello" with value "world"
    client.set("hello", "world".into()).await?;

    // Get key "hello"
    let result = client.get("hello").await?;

    println!("got value from the server; result={:?}", result);

    Ok(())
}

这段代码标注为async异步代码,想确认:

  • 它的执行是否确实是顺序执行?
  • await关键字会确保代码在Future就绪后才继续执行,是否因此导致顺序执行?

回答

没错,这段代码就是顺序执行的,核心原因就是await的作用:

  • 每一个.await都会暂停当前任务,必须等对应的Future完成(比如连接建立成功、set命令执行完毕、get命令拿到结果),才会继续往下走。
  • 这里没有任何并发逻辑,所有操作严格按代码书写顺序依次完成:先建立连接,等连接好再执行set,set完成后再执行get,最后打印结果。
  • 异步不等于一定并发,这段代码只是用异步API完成了一系列有依赖顺序的操作,完全没触发多任务并行或并发的逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 17:54:53