Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

nproc: replace num_cpus crate with thread::available_parallelism #4352

Merged
merged 8 commits into from
Feb 14, 2023
1 change: 0 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion src/uu/nproc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ path = "src/nproc.rs"

[dependencies]
libc = { workspace=true }
num_cpus = { workspace=true }
clap = { workspace=true }
uucore = { workspace=true, features=["fs"] }

Expand Down
23 changes: 16 additions & 7 deletions src/uu/nproc/src/nproc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
// spell-checker:ignore (ToDO) NPROCESSORS nprocs numstr threadstr sysconf

use clap::{crate_version, Arg, ArgAction, Command};
use std::env;
use std::{env, thread};
use uucore::display::Quotable;
use uucore::error::{UResult, USimpleError};
use uucore::format_usage;
Expand Down Expand Up @@ -73,16 +73,16 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
// If OMP_NUM_THREADS=0, rejects the value
let thread: Vec<&str> = threadstr.split_terminator(',').collect();
match &thread[..] {
[] => num_cpus::get(),
[] => available_parallelism(),
[s, ..] => match s.parse() {
Ok(0) | Err(_) => num_cpus::get(),
Ok(0) | Err(_) => available_parallelism(),
Ok(n) => n,
},
}
}
// the variable 'OMP_NUM_THREADS' doesn't exist
// fallback to the regular CPU detection
Err(_) => num_cpus::get(),
Err(_) => available_parallelism(),
}
};

Expand Down Expand Up @@ -127,21 +127,30 @@ fn num_cpus_all() -> usize {
if nprocs == 1 {
// In some situation, /proc and /sys are not mounted, and sysconf returns 1.
// However, we want to guarantee that `nproc --all` >= `nproc`.
num_cpus::get()
available_parallelism()
} else if nprocs > 0 {
nprocs as usize
} else {
1
}
}

// Other platforms (e.g., windows), num_cpus::get() directly.
// Other platforms (e.g., windows), available_parallelism() directly.
#[cfg(not(any(
target_os = "linux",
target_vendor = "apple",
target_os = "freebsd",
target_os = "netbsd"
)))]
fn num_cpus_all() -> usize {
num_cpus::get()
available_parallelism()
}

// In some cases, thread::available_parallelism() may return an Err
// In this case, we will return 1 (like GNU)
fn available_parallelism() -> usize {
match thread::available_parallelism() {
Ok(n) => n.get(),
Err(_) => 1,
}
}