Size Worker Pools With available_parallelism

Read std::thread::available_parallelism, clamp it to a safe worker count, and run one job per worker with scoped threads.

RustResilience

Code

rustsnippet
32 lines
use std::sync::atomic::{AtomicU64, Ordering};
use std::thread;

fn main() {
    // 尊重 cgroup/CPU 亲和性限制,而不是硬编码核心数
    let detected = thread::available_parallelism()
        .map(|n| n.get())
        .unwrap_or(1);
    println!("detected parallelism: {detected}");

    // 留一个核心给主线程与 I/O,且至少保留 1 个 worker
    let workers = detected.saturating_sub(1).max(1);
    println!("worker count: {workers}");

    // scoped 线程允许直接借用栈上的任务列表
    let jobs: Vec<u32> = (0..workers as u32 * 2).collect();
    let total = AtomicU64::new(0);
    thread::scope(|scope| {
        let total = &total;
        for chunk in jobs.chunks(2) {
            scope.spawn(move || {
                let sum: u32 = chunk.iter().sum();
                total.fetch_add(u64::from(sum), Ordering::Relaxed);
            });
        }
    });
    println!(
        "jobs: {} total: {}",
        jobs.len(),
        total.load(Ordering::Relaxed)
    );
}

Inside the snippet

Size Worker Pools With available_parallelism is built around the function main.

Repetition is confined to for chunk in jobs.chunks(2) — the rest of the file is straight-line.

Putting it to use

The demo output is labeled (detected parallelism:, worker count:, jobs:), so every printed line maps back to its originating operation.

Core lines

let sum: u32 = chunk.iter().sum();
let jobs: Vec<u32> = (0..workers as u32 * 2).collect();
.unwrap_or(1);

Interactive Tools for This Topic

FAQ

What does Size Worker Pools With available_parallelism print when run?
Running the file directly is enough — expect labeled output lines such as `detected parallelism:`, `worker count:`, `jobs:`.