Skip to content

Commit

Permalink
openbsd: available_parallelism: use the right API
Browse files Browse the repository at this point in the history
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 vs CPUs configured (and 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
semarie committed Dec 30, 2023
1 parent fe2cfd4 commit 3633f8b
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 3633f8b

Please sign in to comment.