Named Threads With thread::Builder

Create threads with explicit names and stack sizes through thread::Builder so logs and panic messages identify each worker.

RustResilience

Code

rustsnippet
37 lines
use std::thread;

fn main() {
    // Builder 允许设置线程名与栈大小,spawn 失败返回 io::Error
    let named = thread::Builder::new()
        .name("worker-alpha".to_string())
        .stack_size(512 * 1024)
        .spawn(|| {
            println!("running on: {:?}", thread::current().name());
            let sum: u64 = (1..=100).sum();
            println!("sum: {sum}");
        })
        .expect("spawn failed");
    named.join().expect("worker panicked");

    // 多个命名线程便于在调试器与日志里区分
    let mut handles = Vec::new();
    for index in 0..3 {
        let handle = thread::Builder::new()
            .name(format!("job-{index}"))
            .spawn(move || {
                let name = thread::current().name().unwrap_or("unnamed").to_string();
                println!("{name} handling job {index}");
            })
            .expect("spawn failed");
        handles.push(handle);
    }
    for handle in handles {
        handle.join().expect("job panicked");
    }

    // 未命名线程的 name 为 None
    let plain = thread::spawn(|| {
        println!("plain thread name: {:?}", thread::current().name());
    });
    plain.join().expect("plain thread panicked");
}

How the snippet works

Named Threads With thread::Builder is built around the function main.

for index in 0..3 is the loop that carries the per-item work.

Applying it

The demo output is labeled (running on:, sum:, plain thread name:), so every printed line maps back to its originating operation.

Statements that matter

let name = thread::current().name().unwrap_or("unnamed").to_string();
let sum: u64 = (1..=100).sum();

Interactive Tools for This Topic

FAQ

What does Named Threads With thread::Builder print when run?
Invoke the file as-is — the `running on:`, `sum:`, `plain thread name:` prefixes identify which step printed each line.