core: Add cgroupsv2 support to parallel.cpp

The parallel code works out how many CPUs are on the system by checking
the quota it has been assigned in the Linux cgroup. The existing code
works under cgroups v1 but the file structure changed in cgroups v2.
From [1]:

    "cpu.cfs_quota_us" and "cpu.cfs_period_us" are replaced by "cpu.max"
  which contains both quota and period.

This commit add support to parallel so it will read from the cgroups v2
location. v1 support is still retained.

Resolves #25284

[1] 0d5936344f
pull/25285/head
John Slade 1 year ago
parent fc34554475
commit 7f1140b48b
  1. 24
      modules/core/src/parallel.cpp

@ -870,7 +870,22 @@ int getNumberOfCPUsImpl(const char *filename)
#if defined CV_HAVE_CGROUPS #if defined CV_HAVE_CGROUPS
static inline static inline
unsigned getNumberOfCPUsCFS() unsigned getNumberOfCPUsCFSv2()
{
int cfs_quota = 0;
int cfs_period = 0;
std::ifstream ss_cpu_max("/sys/fs/cgroup/cpu.max", std::ios::in | std::ios::binary);
ss_cpu_max >> cfs_quota >> cfs_period;
if (ss_cpu_max.fail() || cfs_quota < 1 || cfs_period < 1) /* values must not be 0 or negative */
return 0;
return (unsigned)max(1, cfs_quota/cfs_period);
}
static inline
unsigned getNumberOfCPUsCFSv1()
{ {
int cfs_quota = 0; int cfs_quota = 0;
{ {
@ -966,8 +981,11 @@ int getNumberOfCPUs_()
static unsigned ncpus_impl_cpuset = (unsigned)getNumberOfCPUsImpl("/sys/fs/cgroup/cpuset/cpuset.cpus"); static unsigned ncpus_impl_cpuset = (unsigned)getNumberOfCPUsImpl("/sys/fs/cgroup/cpuset/cpuset.cpus");
ncpus = minNonZero(ncpus, ncpus_impl_cpuset); ncpus = minNonZero(ncpus, ncpus_impl_cpuset);
static unsigned ncpus_impl_cfs = getNumberOfCPUsCFS(); static unsigned ncpus_impl_cfs_v1 = getNumberOfCPUsCFSv1();
ncpus = minNonZero(ncpus, ncpus_impl_cfs); ncpus = minNonZero(ncpus, ncpus_impl_cfs_v1);
static unsigned ncpus_impl_cfs_v2 = getNumberOfCPUsCFSv2();
ncpus = minNonZero(ncpus, ncpus_impl_cfs_v2);
#endif #endif
static unsigned ncpus_impl_devices = (unsigned)getNumberOfCPUsImpl("/sys/devices/system/cpu/online"); static unsigned ncpus_impl_devices = (unsigned)getNumberOfCPUsImpl("/sys/devices/system/cpu/online");

Loading…
Cancel
Save