Skip to content

Commit

Permalink
Auto merge of #119436 - semarie:openbsd-available_parallelism, r=Mark…
Browse files Browse the repository at this point in the history
…-Simulacrum

openbsd: available_parallelism: use the right API

use the standard `sysconf(_SC_NPROCESSORS_ONLN)` way to get the number of  available processors (capable of running processes), and fallback to `sysctl([CTL_HW, HW_NCPU])` (number of CPUs configured) only on error.

it permits to differenciate CPUs online (capable of running processes) vs CPUs configured (not necessary  capable of running processes).

while here, use the common code path for BSDs for doing that, and avoid code  duplication.

Problem initially reported to me by Jiri Navratil.
  • Loading branch information
bors committed Dec 30, 2023
2 parents e45a937 + 3633f8b commit a2541e8
Showing 1 changed file with 6 additions and 26 deletions.
32 changes: 6 additions & 26 deletions library/std/src/sys/unix/thread.rs
Original file line number Diff line number Diff line change
Expand Up @@ -354,7 +354,12 @@ pub fn available_parallelism() -> io::Result<NonZeroUsize> {
Ok(unsafe { NonZeroUsize::new_unchecked(count) })
}
}
} else if #[cfg(any(target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd"))] {
} else if #[cfg(any(
target_os = "freebsd",
target_os = "dragonfly",
target_os = "openbsd",
target_os = "netbsd",
))] {
use crate::ptr;

#[cfg(target_os = "freebsd")]
Expand Down Expand Up @@ -427,31 +432,6 @@ pub fn available_parallelism() -> io::Result<NonZeroUsize> {
return Err(io::const_io_error!(io::ErrorKind::NotFound, "The number of hardware threads is not known for the target platform"));
}
}
Ok(unsafe { NonZeroUsize::new_unchecked(cpus as usize) })
} else if #[cfg(target_os = "openbsd")] {
use crate::ptr;

let mut cpus: libc::c_uint = 0;
let mut cpus_size = crate::mem::size_of_val(&cpus);
let mut mib = [libc::CTL_HW, libc::HW_NCPU, 0, 0];

let res = unsafe {
libc::sysctl(
mib.as_mut_ptr(),
2,
&mut cpus as *mut _ as *mut _,
&mut cpus_size as *mut _ as *mut _,
ptr::null_mut(),
0,
)
};

// Handle errors if any.
if res == -1 {
return Err(io::Error::last_os_error());
} else if cpus == 0 {
return Err(io::const_io_error!(io::ErrorKind::NotFound, "The number of hardware threads is not known for the target platform"));
}

Ok(unsafe { NonZeroUsize::new_unchecked(cpus as usize) })
} else if #[cfg(target_os = "nto")] {
Expand Down

0 comments on commit a2541e8

Please sign in to comment.