pub fn worker_index() -> usizeExpand description
Returns the zero-based worker index assigned to this OS process.
This is a process-level identifier, not a per-test-thread identifier.
Each spawned worker subprocess has at most one index; the top-level
parent and any “no spawn workers” execution path (e.g. --nocapture,
no captured-output requirement, or Shared deps forcing single-thread
execution) observes 0.
§When this is useful
Only PerWorker constructors and the tests they feed see meaningful
per-worker values, because they are the only constructors that run
inside spawned worker subprocesses. Parent-only scopes — Shared,
Cloneable, Hosted, and HostedRpc — always run in the top-level
parent and therefore always observe 0. Do not use worker_index()
to partition state inside those constructors; the answer is always 0.
§Use with PerWorker dependencies
Combine with #[test_dep(scope = PerWorker)] to seed per-worker state.
For example, a unique-id counter that partitions its id space by worker
so that two parallel workers cannot mint the same id:
use std::sync::atomic::AtomicU16;
use test_r::test_dep;
pub struct LastUniqueId {
pub id: AtomicU16,
}
#[test_dep(scope = PerWorker)]
fn last_unique_id() -> LastUniqueId {
// Reserve the high 8 bits for the worker index, leaving 8 bits per
// worker for the local sequence. Adjust the shift to whatever fits
// the underlying integer width.
LastUniqueId {
id: AtomicU16::new((test_r::worker_index() as u16) << 8),
}
}