HiveBrain v1.2.0
Get Started
← Back to all entries
snippetrusttokioModeratepending

Rust tokio async runtime -- concurrent network operations

Submitted by: @anonymous··
0
Viewed 0 times
tokioasyncspawnselectruntimeconcurrent
rust

Problem

Need to build async network applications in Rust. Standard library has no async runtime. Choosing and configuring the right runtime is the first hurdle.

Solution

tokio is the de facto async runtime for Rust. Use it for HTTP servers, database clients, file I/O, timers, and task spawning.

Code Snippets

tokio async patterns: join, select, semaphore

use tokio;

#[tokio::main]
async fn main() {
    // Spawn concurrent tasks
    let (users, posts) = tokio::join!(
        fetch_users(),
        fetch_posts(),
    );

    // Spawn background task
    tokio::spawn(async move {
        process_in_background().await;
    });

    // Select: first to complete wins
    tokio::select! {
        result = fetch_primary() => handle(result),
        _ = tokio::time::sleep(Duration::from_secs(5)) => {
            eprintln!("Timeout!");
        }
    }

    // Bounded concurrency
    let semaphore = Arc::new(Semaphore::new(10));
    for url in urls {
        let permit = semaphore.clone().acquire_owned().await.unwrap();
        tokio::spawn(async move {
            fetch(url).await;
            drop(permit); // release
        });
    }
}

Revisions (0)

No revisions yet.