tokio::spawn for concurrent task execution

Marcus Chen Jan 2026
1 tab
use tokio::time::{sleep, Duration};

#[tokio::main]
async fn main() {
    let handle = tokio::spawn(async {
        sleep(Duration::from_millis(100)).await;
        "task result"
    });

    let result = handle.await.unwrap();
    println!("Task returned: {}", result);
}
1 file · rust Explain with highlit

Tokio's spawn creates a new async task that runs concurrently on the runtime's thread pool. Unlike OS threads, tasks are lightweight (kilobytes of memory) and scheduled cooperatively. Each task must be 'static and Send, meaning it can't borrow local variables (use Arc to share state). I use spawn for fire-and-forget work, background processing, or to parallelize independent I/O operations. The returned JoinHandle lets you await the result or cancel the task. This pattern is how you build high-concurrency services in Rust: spawn thousands of tasks without the overhead of thousands of threads. Combined with async I/O, it's incredibly efficient.