Ensure CpuInfo::DetectNumberOfCores is > 0 and thread safe.
This CL adds error handling for sysconf, which can return -1 and
adds an RTC_CHECK_GT to ensure the value returned is always greater
than 0.
On top of that CpuInfo::DetectNumberOfCores is made thread safe because
the static local variable is initialized with the right values istead
of 0.
Bug: None
Change-Id: I294684e7380b12cda55ec8d6c7a90e132dc3af85
Reviewed-on: https://webrtc-review.googlesource.com/c/src/+/138210
Commit-Queue: Mirko Bonadei <mbonadei@webrtc.org>
Reviewed-by: Niels Moller <nisse@webrtc.org>
Cr-Commit-Position: refs/heads/master@{#28057}
diff --git a/system_wrappers/source/cpu_info.cc b/system_wrappers/source/cpu_info.cc
index 6bcdd5f..7288c67 100644
--- a/system_wrappers/source/cpu_info.cc
+++ b/system_wrappers/source/cpu_info.cc
@@ -24,8 +24,7 @@
namespace internal {
static int DetectNumberOfCores() {
- // We fall back on assuming a single core in case of errors.
- int number_of_cores = 1;
+ int number_of_cores;
#if defined(WEBRTC_WIN)
SYSTEM_INFO si;
@@ -33,6 +32,10 @@
number_of_cores = static_cast<int>(si.dwNumberOfProcessors);
#elif defined(WEBRTC_LINUX) || defined(WEBRTC_ANDROID)
number_of_cores = static_cast<int>(sysconf(_SC_NPROCESSORS_ONLN));
+ if (number_of_cores < 0) {
+ RTC_LOG(LS_ERROR) << "Failed to get number of cores";
+ number_of_cores = 1;
+ }
#elif defined(WEBRTC_MAC) || defined(WEBRTC_IOS)
int name[] = {CTL_HW, HW_AVAILCPU};
size_t size = sizeof(number_of_cores);
@@ -44,10 +47,12 @@
number_of_cores = zx_system_get_num_cpus();
#else
RTC_LOG(LS_ERROR) << "No function to get number of cores";
+ number_of_cores = 1;
#endif
RTC_LOG(LS_INFO) << "Available number of cores: " << number_of_cores;
+ RTC_CHECK_GT(number_of_cores, 0);
return number_of_cores;
}
} // namespace internal
@@ -59,9 +64,8 @@
// is running in a sandbox, we may only be able to read the value once (before
// the sandbox is initialized) and not thereafter.
// For more information see crbug.com/176522.
- static uint32_t logical_cpus = 0;
- if (!logical_cpus)
- logical_cpus = static_cast<uint32_t>(internal::DetectNumberOfCores());
+ static const uint32_t logical_cpus =
+ static_cast<uint32_t>(internal::DetectNumberOfCores());
return logical_cpus;
}