mcpField
R
rust-async-internals

rust-async-internals

github.com/mohitmishra786开发269480 次安装18 周前更新
代码仓库

关于 rust-async-internals

为 Agent 讲解 Rust 异步机制及其常见调试问题,面向开发和排查异步 Rust 程序的开发者。内容包括 Future 轮询、Pin、Tokio 任务、阻塞调用及 select! 和 join! 的注意事项。

主要功能

  1. 01Future 与 poll 执行模型
  2. 02Pin 和 Unpin 的作用
  3. 03Tokio 任务模型
  4. 04使用 tokio-console 检查异步任务
  5. 05异步阻塞与 select! 陷阱

适用场景

  1. 01理解 async/await 的执行方式
  2. 02排查异步程序性能问题
  3. 03检查 Tokio 任务及唤醒器问题
  4. 04避免阻塞调用和 select! 分支取消问题

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/mohitmishra786/low-level-dev-skills --skill rust-async-internals

安装后在 Claude Code 中输入/rust-async-internals确认已加载。

详细介绍

Rust 异步内部机制

用途

引导 Agent 了解 Rust 的 async/await 内部机制:Future trait 和轮询循环、用于自引用类型的 Pin/Unpin、tokio 的任务模型、使用 tokio-console 诊断异步堆栈跟踪、查找 waker 泄漏,以及 select!/join! 的常见陷阱。

触发条件

  • “Rust 的 async/await 实际上是如何工作的?”
  • “Rust 异步中的 Pin 和 Unpin 是什么?”
  • “我的异步代码很慢——该如何分析?”
  • “如何使用 tokio-console 调试异步任务?”
  • “我在异步代码中有一个阻塞调用——该怎么办?”
  • “select! 是如何工作的,有哪些陷阱?”

工作流

1. Future trait——轮询模型
// std::future::Future (simplified)
pub trait Future {
    type Output;
    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>;
}

pub enum Poll<T> {
    Ready(T),    // computation done, T is the result
    Pending,     // not ready yet, waker registered, will be polled again
}

执行模型:

  1. 调用 .await 会对 future 调用 poll()
  2. 如果为 Pending:当前任务会注册其 waker,并将控制权交还给运行时
  3. waker 触发时(I/O 就绪、计时器触发),运行时会再次轮询
  4. 如果为 Ready(val):.await 表达式的求值结果为 val
2. 实现一个简单的 Future
use std::{
    future::Future,
    pin::Pin,
    task::{Context, Poll},
    time::{Duration, Instant},
};

struct Delay { deadline: Instant }

impl Delay {
    fn new(dur: Duration) -> Self {
        Delay { deadline: Instant::now() + dur }
    }
}

impl Future for Delay {
    type Output = ();

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
        if Instant::now() >= self.deadline {
            Poll::Ready(())
        } else {
            // Register the waker — runtime calls waker.wake() to re-poll
            // In production: register with I/O reactor or timer wheel
            let waker = cx.waker().clone();
            let deadline = self.deadline;
            std::thread::spawn(move || {
                let now = Instant::now();
                if deadline > now {
                    std::thread::sleep(deadline - now);
                }
                waker.wake();  // notify runtime to re-poll
            });
            Poll::Pending
        }
    }
}

// Usage
async fn main() {
    Delay::new(Duration::from_secs(1)).await;
    println!("Done");
}
3. Pin 和 Unpin

Pin<P> 可防止移动指针 P 指向的值。这很重要,因为异步状态机包含自引用指针(指向 future 所在同一结构体内部的引用):

// Why Pin is needed: async fn compiles to a state machine struct
// that may have self-references across await points

async fn example() {
    let data = vec![1, 2, 3];
    let ref_to_data = &data;              // reference into same stack frame
    some_async_op().await;                // suspension point
    println!("{:?}", ref_to_data);       // reference still used after suspend
}
// The state machine stores both `data` and `ref_to_data`.
// If the struct were moved, `ref_to_data` would dangle.
// Pin<&mut State> prevents moving the state machine.

// Unpin: a marker trait for types that are safe to move even when pinned
// Most types implement Unpin automatically
// Futures generated by async/await do NOT implement Unpin

// Creating a Pin from Box (heap allocation → safe)
let boxed: Pin<Box<dyn Future<Output = ()>>> = Box::pin(my_future);

// Pinning to stack (unsafe, use pin! macro)
use std::pin::pin;
let fut = pin!(my_future);
fut.await;   // or poll it directly
4. tokio 任务模型
use tokio::task;

// Spawn a task (runs concurrently on the runtime thread pool)
let handle = tokio::spawn(async {
    // ... async work ...
    42
});
let result = handle.await.unwrap();  // wait for completion

// spawn_blocking — for CPU-bound or blocking I/O
let result = task::spawn_blocking(|| {
    // runs on a dedicated blocking thread pool
    std::fs::read_to_string("big_file.txt")
}).await.unwrap();

// yield to runtime (cooperative multitasking)
tokio::task::yield_now().await;

// LocalSet — for !Send futures (single-threaded)
let local = task::LocalSet::new();
local.run_until(async {
    task::spawn_local(async { /* !Send future */ }).await.unwrap();
}).await;
5. tokio-console——异步任务检查器
# Cargo.toml
[dependencies]
console-subscriber = "0.3"
tokio = { version = "1", features = ["full", "tracing"] }
// main.rs
fn main() {
    console_subscriber::init();  // must be called before tokio runtime
    tokio::runtime::Builder::new_multi_thread()
        .enable_all()
        .build()
        .unwrap()
        .block_on(async_main());
}
# Install tokio-console CLI
cargo install --locked tokio-console

# Run your app with tracing enabled
RUSTFLAGS="--cfg tokio_unstable" cargo run

# In another terminal, connect tokio-console
tokio-console

# tokio-console shows:
# - Running tasks with their names, poll times, and wakeup counts
# - Slow tasks (high poll duration = blocking in async!)
# - Tasks that have been pending for a long time (stuck?)
# - Resource contention (mutex/semaphore wait times)
6. 在异步代码中阻塞——常见错误
// WRONG: blocking call in async context blocks entire thread
async fn bad() {
    std::thread::sleep(Duration::from_secs(1));  // blocks runtime thread!
    std::fs::read_to_string("file.txt").unwrap(); // blocking I/O blocks runtime!
}

// CORRECT: use async equivalents
async fn good() {
    tokio::time::sleep(Duration::from_secs(1)).await;   // async sleep
    tokio::fs::read_to_string("file.txt").await.unwrap(); // async I/O
}

// CORRECT: if you must block, use spawn_blocking
async fn with_blocking() {
    let content = tokio::task::spawn_blocking(|| {
        heavy_cpu_computation()   // runs on blocking thread pool
    }).await.unwrap();
}
7. select! 和 join! 的陷阱
use tokio::select;

// select! — complete when FIRST branch completes, cancels others
select! {
    result = fetch_a() => println!("A: {:?}", result),
    result = fetch_b() => println!("B: {:?}", result),
    // Pitfall: the LOSING branches are DROPPED immediately
    // If fetch_a wins, fetch_b's future is dropped (and its state machine cleaned up)
    // This is correct and safe — but can be surprising
}

// join! — wait for ALL to complete
let (a, b) = tokio::join!(fetch_a(), fetch_b());

// Biased select (always check first branch first)
loop {
    select! {
        biased;                        // prevents fairness, checks in order
        _ = shutdown_signal.recv() => break,
        msg = queue.recv() => process(msg),
    }
}

// select! with values from loop (use fuse)
let mut fut = some_future().fuse();   // FusedFuture: safe to poll after completion
loop {
    select! {
        val = &mut fut => { /* ... */ break; }
        _ = interval.tick() => { /* periodic work */ }
    }
}

相关技能

  • 使用 skills/rust/rust-debugging 调试异步 Rust 程序的 GDB/LLDB
  • 使用 skills/rust/rust-profiling 分析带有异步堆栈帧的 cargo-flamegraph
  • 使用 skills/low-level-programming/cpp-coroutines 对比 C++20 协程
  • 使用 skills/low-level-programming/memory-model 了解异步上下文中的内存排序

评论

支持 Markdown