Skip to content

take into account the num of processes by ulimit #143614

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 54 additions & 2 deletions library/std/src/sys/pal/unix/thread.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use crate::sys::weak::dlsym;
use crate::sys::weak::weak;
use crate::sys::{os, stack_overflow};
use crate::time::{Duration, Instant};
use crate::{cmp, io, ptr};
use crate::{cmp, fs, io, ptr};
#[cfg(not(any(
target_os = "l4re",
target_os = "vxworks",
Expand Down Expand Up @@ -405,6 +405,41 @@ fn truncate_cstr<const MAX_WITH_NUL: usize>(cstr: &CStr) -> [libc::c_char; MAX_W
result
}

fn count_user_threads() -> Result<usize, io::Error> {
let current_uid = unsafe { libc::getuid() };
let mut thread_count = 0;

for entry in fs::read_dir("/proc")? {
let entry = entry?;
let pid = entry.file_name().to_string_lossy().to_string();

if let Ok(_pid_num) = pid.parse::<u32>() {
let status_path = format!("/proc/{}/status", pid);

if let Ok(status) = fs::read_to_string(status_path) {
let mut uid: Option<libc::uid_t> = None;
let mut threads: Option<usize> = None;

for line in status.lines() {
if line.starts_with("Uid:") {
uid = line.split_whitespace().nth(1).and_then(|s| s.parse().ok());
} else if line.starts_with("Threads:") {
threads = line.split_whitespace().nth(1).and_then(|s| s.parse().ok());
}
}

if let (Some(uid), Some(t)) = (uid, threads) {
if uid == current_uid {
thread_count += t;
}
}
}
}
}

Ok(thread_count)
}

pub fn available_parallelism() -> io::Result<NonZero<usize>> {
cfg_if::cfg_if! {
if #[cfg(any(
Expand All @@ -420,6 +455,7 @@ pub fn available_parallelism() -> io::Result<NonZero<usize>> {
#[allow(unused_assignments)]
#[allow(unused_mut)]
let mut quota = usize::MAX;
let mut ulimit = libc::rlim_t::MAX;

#[cfg(any(target_os = "android", target_os = "linux"))]
{
Expand All @@ -439,14 +475,30 @@ pub fn available_parallelism() -> io::Result<NonZero<usize>> {
}
}
}

let mut r: libc::rlimit = unsafe { mem::zeroed() };
unsafe {
if libc::getrlimit(libc::RLIMIT_NPROC, &mut r) == 0 {
match r.rlim_cur {
libc::RLIM_INFINITY => ulimit = libc::rlim_t::MAX,
soft_limit => {
ulimit = match count_user_threads() {
Ok(t) => soft_limit - t as libc::rlim_t,
_ => 1
}
}
}
}
}
}

match unsafe { libc::sysconf(libc::_SC_NPROCESSORS_ONLN) } {
-1 => Err(io::Error::last_os_error()),
0 => Err(io::Error::UNKNOWN_THREAD_COUNT),
cpus => {
let count = cpus as usize;
// Cover the unusual situation where we were able to get the quota but not the affinity mask
let count = count.min(quota);
let count = count.min(quota.min(ulimit.try_into().unwrap_or(usize::MAX)));
Ok(unsafe { NonZero::new_unchecked(count) })
}
}
Expand Down
3 changes: 3 additions & 0 deletions library/std/src/thread/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2012,6 +2012,9 @@ fn _assert_sync_and_send() {
/// which may take time on systems with large numbers of mountpoints.
/// (This does not apply to cgroup v2, or to processes not in a
/// cgroup.)
/// - If was set _ulimit_ restrictions for maximum number of processes that can be
/// created for the real user ID (`ulimit -u`), then result will be arithmetic difference
/// of _soft-limit_ and number working threads at the moment
///
/// On all targets:
/// - It may overcount the amount of parallelism available when running in a VM
Expand Down
Loading