First Result Wins With Scope Threads

Race scoped worker threads through an mpsc channel, skip failed replicas, and keep the first successful answer while the scope joins the losers.

RustResilience

Code

rustsnippet
42 lines
use std::sync::mpsc;
use std::thread;
use std::time::Duration;

fn main() {
    let replicas = [
        ("replica-a", 30, false),
        ("replica-b", 10, true),
        ("replica-c", 20, false),
    ];
    let (tx, rx) = mpsc::channel::<Option<String>>();

    // scope 允许借用栈上的 replicas:三个副本并发探测
    thread::scope(|s| {
        for (name, delay, fail) in replicas {
            let tx = tx.clone();
            s.spawn(move || {
                thread::sleep(Duration::from_millis(delay));
                let outcome = if fail { None } else { Some(format!("{name}: ok")) };
                let _ = tx.send(outcome);
            });
        }
        // 主发送端在 scope 内显式 drop:全部失败时 recv 以 Err 结束而不是挂起
        drop(tx);

        // 跳过失败副本,留下最先成功的一个
        let winner = loop {
            match rx.recv() {
                Ok(Some(answer)) => break Some(answer),
                Ok(None) => continue,
                Err(_) => break None,
            }
        };
        match winner {
            Some(answer) => println!("winner: {answer}"),
            None => println!("all replicas failed"),
        }
    });

    // scope 结束时自动 join:输掉的副本随后才完成,结果被丢弃
    println!("raced {} replicas", replicas.len());
}

How it works

The moving parts are the function main.

The cycling part of this snippet is for (name, delay, fail) in replicas. Branching goes through match, whose exhaustiveness checking turns forgotten cases into compile errors.

What to watch for

  • The language toolchain on its own is the only prerequisite to meet.

Using it

The entry-point signature is fn main()

The demo output is labeled (winner:, all replicas failed, raced); each label names the call that printed it.

Key statements

let outcome = if fail { None } else { Some(format!("{name}: ok")) };
match rx.recv() {
    Ok(Some(answer)) => break Some(answer),
    Ok(None) => continue,
    Err(_) => break None,
}
match winner {
    Some(answer) => println!("winner: {answer}"),
    None => println!("all replicas failed"),
}

Interactive Tools for This Topic

FAQ

What does First Result Wins With Scope Threads print when run?
Execute the whole file; each printed line is prefixed with a label like `winner:`, `all replicas failed`, `raced`.