Skip to content

Commit

Permalink
Rollup merge of rust-lang#89310 - joshtriplett:available-concurrency-…
Browse files Browse the repository at this point in the history
…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.
  • Loading branch information
matthiaskrgr authored Oct 15, 2021
2 parents c102653 + 433439e commit b8283bd
Showing 1 changed file with 8 additions and 0 deletions.
8 changes: 8 additions & 0 deletions library/std/src/sys/unix/thread.rs
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,14 @@ pub fn available_parallelism() -> io::Result<NonZeroUsize> {
target_os = "solaris",
target_os = "illumos",
))] {
#[cfg(any(target_os = "android", target_os = "linux"))]
{
let mut set: libc::cpu_set_t = unsafe { mem::zeroed() };
if unsafe { libc::sched_getaffinity(0, mem::size_of::<libc::cpu_set_t>(), &mut set) } == 0 {
let count = unsafe { libc::CPU_COUNT(&set) };
return Ok(unsafe { NonZeroUsize::new_unchecked(count as usize) });
}
}
match unsafe { libc::sysconf(libc::_SC_NPROCESSORS_ONLN) } {
-1 => Err(io::Error::last_os_error()),
0 => Err(io::Error::new_const(io::ErrorKind::NotFound, &"The number of hardware threads is not known for the target platform")),
Expand Down

0 comments on commit b8283bd

Please sign in to comment.