实现说明
thread::Builder 命名线程以函数 main为骨架。
for index in 0..3 承担全部的逐项处理。
使用要点
- 每一步打印都带着自己的标签:
running on:、sum:、plain thread name:。
常见问题
运行「thread::Builder 命名线程」会打印什么?
运行文件本身,running on:、sum:、plain thread name: 这些前缀各对应一段演示逻辑。
核心语句
let name = thread::current().name().unwrap_or("unnamed").to_string();
let sum: u64 = (1..=100).sum();
代码示例
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");
}