On 1 November 2011 17:06, Mike Stump wrote: > On Nov 1, 2011, at 8:55 AM, Jonathan Wakely wrote: >> Is there a reason you used "hw.ncpu" not the constant HW_NCPU ? > > I suspect on some systems, this would be a runtime value.... so, no fixed > constant could ever work.
It's a constant for identifying the sysctl, not a constant for the number of processors e.g. (untested) int mib[] = { CTL_HW, HW_NCPU }; if (!sysctl(mib, 2, &count, &size, NULL, 0)) The Mac OS X man page says "the sysctl() function runs in about a third the time as the same request made via the sysctlbyname() function." My preferred solution (which would be consistent with the existing code, and additionally support NetBSD, OpenBSD and Irix) would be to add autoconf tests for the required functionality, then: #if defined(_GLIBCXX_USE_GET_NPROCS) # include <sys/sysinfo.h> # define _GLIBCXX_NPROCS get_nprocs() #elif defined(_GLIBCXX_USE_SC_NPROCESSORS_ONLN) # include <unistd.h> # define _GLIBCXX_NPROCS sysconf(_SC_NPROCESSORS_ONLN) #elif defined(_GLIBCXX_USE_SC_NPROC_ONLN) # include <unistd.h> # define _GLIBCXX_NPROCS sysconf(_SC_NPROC_ONLN) #elif defined(_GLIBCXX_USE_PTHREADS_NUM_PROCESSORS_NP) # define _GLIBCXX_NPROCS pthread_num_processors_np() #elif defined(_GLIBCXX_USE_SYSCTLBYNAME_HW_NCPU) # include <sys/sysctl.h> static inline int get_nprocs() { int count; size_t size = sizeof(count); int mib[] = { CTL_HW, HW_NCPU }; if (!sysctl(mib, 2, &count, &size, NULL, 0)) return count; return 0; } # define _GLIBCXX_NPROCS get_nprocs() #else # define _GLIBCXX_NPROCS 0 #endif ... unsigned int thread::hardware_concurrency() noexcept { int __n = _GLIBCXX_NPROCS; if (__n < 0) __n = 0; return __n; }