Skip to content

Commit 7c9611d

Browse files
committed
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.
1 parent 23be29a commit 7c9611d

File tree

1 file changed

+8
-0
lines changed

1 file changed

+8
-0
lines changed

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

Lines changed: 8 additions & 0 deletions
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)