Performance

When to Use Async vs Threads in Rust

Use threads for CPU-bound tasks that require true parallelism across multiple cores, and use async for I/O-bound tasks that need to handle many concurrent operations efficiently on a single thread. Threads leverage the OS scheduler to run code simultaneously, while async uses a runtime to multiplex

Performance: When to Use Async vs Threads in Rust

Use threads for CPU-bound tasks that require true parallelism across multiple cores, and use async for I/O-bound tasks that need to handle many concurrent operations efficiently on a single thread. Threads leverage the OS scheduler to run code simultaneously, while async uses a runtime to multiplex many tasks without blocking.

// CPU-bound: Use threads for parallel computation
use std::thread;

fn main() {
    let handle = thread::spawn(|| {
        // Heavy calculation runs on a separate OS thread
        let sum: i32 = (0..1_000_000).sum();
        sum
    });
    let _result = handle.join().unwrap();
}
// I/O-bound: Use async for high-concurrency network/file operations
use tokio;

#[tokio::main]
async fn main() {
    // Non-blocking I/O runs on a single thread pool
    let _response = tokio::net::TcpStream::connect("127.0.0.1:8080").await;
}