异步主函数 ​

核心概念 ​

Rust 的标准 main 函数是同步的,不能直接声明为 async fn main()。要在 main 中运行异步代码,需要一个异步运行时(runtime)来驱动 Future 的执行。最常用的方式是使用 #[tokio::main] 宏(或 #[async_std::main]),它会自动创建运行时并在其中执行 async fn main() 的函数体。这个宏实际上是语法糖,底层创建了一个 tokio::runtime::Runtime,调用 block_on 来执行异步主函数。你也可以手动创建运行时来获得更精细的控制。

rust
// 最常用的方式:使用 #[tokio::main] 宏
// Cargo.toml 需要:tokio = { version = "1", features = ["full"] }

use tokio::time::{sleep, Duration};

#[tokio::main]
async fn main() {
    // 现在可以在 main 中使用 .await
    println!("异步主函数开始");
    sleep(Duration::from_millis(100)).await;
    println!("异步主函数结束");
}

// #[tokio::main] 展开后大致等价于:
// fn main() {
//     tokio::runtime::Builder::new_multi_thread()
//         .enable_all()
//         .build()
//         .unwrap()
//         .block_on(async {
//             println!("异步主函数开始");
//             sleep(Duration::from_millis(100)).await;
//             println!("异步主函数结束");
//         });
// }

手动创建运行时 ​

rust
use tokio::runtime::Runtime;
use tokio::time::{sleep, Duration};

fn main() {
    // 手动创建多线程运行时
    let rt = Runtime::new().unwrap();

    // block_on:阻塞当前线程直到 Future 完成
    let result = rt.block_on(async {
        sleep(Duration::from_millis(100)).await;
        "异步任务完成"
    });
    println!("{}", result);

    // 也可以在运行时中 spawn 任务
    rt.block_on(async {
        let handle = tokio::spawn(async {
            sleep(Duration::from_millis(50)).await;
            42
        });

        let value = handle.await.unwrap();
        println!("spawn 结果: {}", value);
    });
}

运行时配置选项 ​

rust
use tokio::runtime;
use tokio::time::{sleep, Duration};

fn main() {
    // === 多线程运行时(默认)===
    // 使用多个操作系统线程执行异步任务
    let multi_rt = runtime::Builder::new_multi_thread()
        .worker_threads(4)        // 工作线程数量
        .enable_all()             // 启用所有功能(IO、时间等)
        .thread_name("my-worker") // 线程名称
        .build()
        .unwrap();

    multi_rt.block_on(async {
        println!("多线程运行时");
        let handles: Vec<_> = (0..4).map(|i| {
            tokio::spawn(async move {
                sleep(Duration::from_millis(50)).await;
                println!("  任务{} 在线程 {:?}", i, std::thread::current().id());
            })
        }).collect();

        for h in handles {
            h.await.unwrap();
        }
    });

    // === 单线程运行时 ===
    // 所有异步任务在一个线程上执行
    // 适合不需要多线程的场景,开销更小
    let single_rt = runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .unwrap();

    single_rt.block_on(async {
        println!("\n单线程运行时");
        sleep(Duration::from_millis(50)).await;
        println!("  在线程 {:?}", std::thread::current().id());
    });
}
运行时类型宏写法线程适用场景
多线程#[tokio::main]多个工作线程服务器、高并发
单线程#[tokio::main(flavor = "current_thread")]当前线程工具、脚本、嵌入式

#[tokio::main] 的变体 ​

rust
// === 默认多线程 ===
// #[tokio::main]
// async fn main() { ... }

// === 单线程 ===
// #[tokio::main(flavor = "current_thread")]
// async fn main() { ... }

// === 指定工作线程数 ===
// #[tokio::main(worker_threads = 2)]
// async fn main() { ... }

// 这里用默认的多线程模式演示
use tokio::time::{sleep, Duration};

#[tokio::main]
async fn main() {
    // === main 函数的返回值 ===
    // async main 可以返回 Result
    // 需要改为:async fn main() -> Result<(), Box<dyn std::error::Error>>
    // 这里用内部函数演示

    async fn run() -> Result<String, String> {
        sleep(Duration::from_millis(50)).await;
        Ok("运行成功".to_string())
    }

    match run().await {
        Ok(msg) => println!("{}", msg),
        Err(e) => eprintln!("错误: {}", e),
    }

    // main 中可以使用所有异步功能
    let (r1, r2) = tokio::join!(
        async { sleep(Duration::from_millis(50)).await; "任务1" },
        async { sleep(Duration::from_millis(50)).await; "任务2" },
    );
    println!("{}, {}", r1, r2);
}

没有运行时时的替代方案 ​

rust
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll, RawWaker, RawWakerVTable, Waker};

// 极简的 block_on 实现(仅用于理解原理)
// 实际项目中应使用 tokio 或 async-std
fn simple_block_on<F: Future>(mut future: F) -> F::Output {
    // 创建一个最简单的 Waker(什么都不做)
    fn dummy_raw_waker() -> RawWaker {
        fn no_op(_: *const ()) {}
        fn clone(_: *const ()) -> RawWaker { dummy_raw_waker() }
        let vtable = &RawWakerVTable::new(clone, no_op, no_op, no_op);
        RawWaker::new(std::ptr::null(), vtable)
    }

    let waker = unsafe { Waker::from_raw(dummy_raw_waker()) };
    let mut cx = Context::from_waker(&waker);

    // 安全地 pin future 到栈上
    let mut future = unsafe { Pin::new_unchecked(&mut future) };

    // 反复 poll 直到完成
    loop {
        match future.as_mut().poll(&mut cx) {
            Poll::Ready(val) => return val,
            Poll::Pending => {
                // 真正的运行时会在这里等待事件
                // 这个简化版只是忙等待
                std::thread::yield_now();
            }
        }
    }
}

fn main() {
    // 用我们的简化 block_on 执行一个简单的 Future
    let result = simple_block_on(async {
        let a = 10;
        let b = 20;
        a + b
    });
    println!("简化 block_on: {}", result);

    // 注意:这个简化版不支持 tokio::time::sleep 等功能
    // 因为没有事件循环和定时器
    // 真正的应用请使用 tokio

    // 也可以用 futures crate 的 block_on
    // futures::executor::block_on(async { ... })
}

基本示例 ​

展示不同方式启动异步主函数以及运行时的生命周期管理:

rust
use tokio::time::{sleep, Duration, Instant};

// 异步应用入口
async fn app_main() -> Result<(), Box<dyn std::error::Error>> {
    let start = Instant::now();

    // 初始化
    println!("=== 应用启动 ===");
    let config = load_config().await?;
    println!("配置加载: {}", config);

    // 并发启动多个服务
    let (db, cache) = tokio::join!(
        init_database(),
        init_cache(),
    );
    println!("数据库: {}", db);
    println!("缓存: {}", cache);

    // 模拟处理请求
    println!("\n=== 处理请求 ===");
    let mut handles = Vec::new();

    for i in 1..=5 {
        handles.push(tokio::spawn(async move {
            sleep(Duration::from_millis(50 * i)).await;
            format!("请求{} 完成", i)
        }));
    }

    for handle in handles {
        println!("  {}", handle.await?);
    }

    // 优雅关闭
    println!("\n=== 关闭 ===");
    shutdown().await;
    println!("总运行时间: {:?}", start.elapsed());

    Ok(())
}

async fn load_config() -> Result<String, Box<dyn std::error::Error>> {
    sleep(Duration::from_millis(50)).await;
    Ok("default".to_string())
}

async fn init_database() -> String {
    sleep(Duration::from_millis(100)).await;
    "PostgreSQL 已连接".to_string()
}

async fn init_cache() -> String {
    sleep(Duration::from_millis(80)).await;
    "Redis 已连接".to_string()
}

async fn shutdown() {
    sleep(Duration::from_millis(30)).await;
    println!("  资源已释放");
}

#[tokio::main]
async fn main() {
    // 方式1:直接在 async main 中运行
    if let Err(e) = app_main().await {
        eprintln!("应用错误: {}", e);
        std::process::exit(1);
    }

    // 方式2(备选):手动创建运行时
    // fn main() {
    //     let rt = tokio::runtime::Runtime::new().unwrap();
    //     if let Err(e) = rt.block_on(app_main()) {
    //         eprintln!("应用错误: {}", e);
    //         std::process::exit(1);
    //     }
    // }
}

常见问题 ​

问题一:#[tokio::main] 和手动创建 Runtime 哪个好?

#[tokio::main] 更简洁,适合大多数应用。手动创建 Runtime 适合需要精细控制的场景:在库代码中使用(不应强制用户用特定运行时)、需要在同步代码中嵌入异步逻辑、需要多个独立的运行时实例。

问题二:可以嵌套 block_on 吗?

不可以。在已经运行的 tokio 运行时中再调用 block_on 会 panic。如果在异步代码中需要执行另一个异步操作,用 .await 而不是 block_on。

问题三:多线程和单线程运行时怎么选?

多线程运行时能利用多核 CPU,适合服务端应用。单线程运行时开销更小,适合命令行工具、脚本、资源受限的环境。如果不确定,用默认的多线程。

问题四:async main 可以返回 Result 吗?

可以。写成 async fn main() -> Result<(), Box<dyn std::error::Error>>,这样可以在 main 中使用 ? 操作符。

适用场景 ​

  • 应用入口:Web 服务器、命令行工具的异步入口
  • 测试:#[tokio::test] 用于异步测试函数
  • 嵌入异步:在同步代码中通过手动 Runtime 嵌入异步逻辑
  • 库开发:手动创建 Runtime 避免依赖特定运行时

注意事项 ​

  • 标准 fn main() 不能是 async,需要运行时宏或手动创建 Runtime
  • #[tokio::main] 默认创建多线程运行时
  • 不要在运行中的运行时内部嵌套 block_on
  • block_on 会阻塞当前线程直到 Future 完成
  • #[tokio::test] 提供异步测试支持
  • 单线程运行时用 flavor = "current_thread" 配置

总结 ​

Rust 的 main 函数不能直接是 async 的,需要异步运行时来驱动 Future 执行。#[tokio::main] 宏是最简便的方式,它自动创建运行时并执行 async main 函数体。底层等价于创建 tokio::runtime::Runtime 并调用 block_on。运行时有多线程和单线程两种模式,多线程适合服务端高并发,单线程适合轻量工具。手动创建运行时提供更精细的控制,适合库代码和需要在同步代码中嵌入异步逻辑的场景。不能在已运行的运行时中嵌套 block_on。async main 可以返回 Result 以支持 ? 操作符。