about summary refs log tree commit diff
diff options
context:
space:
mode:
authorbors <bors@rust-lang.org>2021-11-07 11:53:25 +0000
committerbors <bors@rust-lang.org>2021-11-07 11:53:25 +0000
commitfecfc0e6cc78d74d5898f168cfeee81256ac9ac7 (patch)
tree77ba1cbacf4e50cbd7afd041f94088f73dc77cb7
parent90a273b785b3bc482b82c4896ba1bdea68745e46 (diff)
parent7c9611d124cc0bf127a0d83d75617445f70c422a (diff)
downloadrust-fecfc0e6cc78d74d5898f168cfeee81256ac9ac7.tar.gz
rust-fecfc0e6cc78d74d5898f168cfeee81256ac9ac7.zip
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.
-rw-r--r--library/std/src/sys/unix/thread.rs8
1 files changed, 8 insertions, 0 deletions
diff --git a/library/std/src/sys/unix/thread.rs b/library/std/src/sys/unix/thread.rs
index 6f4863057ab..b99eb2e553f 100644
--- a/library/std/src/sys/unix/thread.rs
+++ b/library/std/src/sys/unix/thread.rs
@@ -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")),