Skip to content

Commit fecfc0e

Browse files
committed
Auto merge of #89310 - joshtriplett:available-concurrency-affinity, r=m-ou-se
Make `std::thread::available_concurrency` support process-limited number of CPUs Use `libc::sched_getaffinity` and count the number of CPUs in the returned mask. This handles cases where the process doesn't have access to all CPUs, such as when limited via `taskset` or similar. This also covers cgroup cpusets.
2 parents 90a273b + 7c9611d commit fecfc0e

File tree

1 file changed

+8
-0
lines changed

1 file changed

+8
-0
lines changed

library/std/src/sys/unix/thread.rs

+8
Original file line numberDiff line numberDiff line change
@@ -275,6 +275,14 @@ pub fn available_parallelism() -> io::Result<NonZeroUsize> {
275275
target_os = "solaris",
276276
target_os = "illumos",
277277
))] {
278+
#[cfg(any(target_os = "android", target_os = "linux"))]
279+
{
280+
let mut set: libc::cpu_set_t = unsafe { mem::zeroed() };
281+
if unsafe { libc::sched_getaffinity(0, mem::size_of::<libc::cpu_set_t>(), &mut set) } == 0 {
282+
let count = unsafe { libc::CPU_COUNT(&set) };
283+
return Ok(unsafe { NonZeroUsize::new_unchecked(count as usize) });
284+
}
285+
}
278286
match unsafe { libc::sysconf(libc::_SC_NPROCESSORS_ONLN) } {
279287
-1 => Err(io::Error::last_os_error()),
280288
0 => Err(io::Error::new_const(io::ErrorKind::NotFound, &"The number of hardware threads is not known for the target platform")),

0 commit comments

Comments
 (0)