Commit d7f74150 authored by Vicențiu Ciorbaru's avatar Vicențiu Ciorbaru

Check for CPU_COUNT macro within my_getncpus

* Small refactor of my_getncpus function to compile for very old glibc < 2.6.
* Cleanup code to eliminate duplication.
parent 66105321
...@@ -30,50 +30,52 @@ static int ncpus=0; ...@@ -30,50 +30,52 @@ static int ncpus=0;
int my_getncpus(void) int my_getncpus(void)
{ {
#if (defined(__linux__) || defined(__FreeBSD__)) && defined(HAVE_PTHREAD_GETAFFINITY_NP)
cpu_set_t set;
if (!ncpus) if (!ncpus)
{ {
/*
First attempt to get the total number of available cores. sysconf is
the fallback, but it can return a larger number. It will return the
total number of cores, not the ones available to the process - as
configured via core affinity.
*/
#if (defined(__linux__) || defined(__FreeBSD__)) && defined(HAVE_PTHREAD_GETAFFINITY_NP)
cpu_set_t set;
if (pthread_getaffinity_np(pthread_self(), sizeof(set), &set) == 0) if (pthread_getaffinity_np(pthread_self(), sizeof(set), &set) == 0)
{ {
#ifdef CPU_COUNT
/* CPU_COUNT was introduced with glibc 2.6. */
ncpus= CPU_COUNT(&set); ncpus= CPU_COUNT(&set);
}
else
{
#ifdef _SC_NPROCESSORS_ONLN
ncpus= sysconf(_SC_NPROCESSORS_ONLN);
#else #else
ncpus= 2; /* Implementation for platforms with glibc < 2.6 */
size_t i;
for (i= 0; i < CPU_SETSIZE; i++)
if (CPU_ISSET(i, &set))
ncpus++;
#endif #endif
return ncpus;
} }
} #endif /* (__linux__ || __FreeBSD__) && HAVE_PTHREAD_GETAFFINITY_NP */
#else /* __linux__ || FreeBSD && HAVE_PTHREAD_GETAFFINITY_NP */
if (!ncpus)
{
#ifdef _SC_NPROCESSORS_ONLN #ifdef _SC_NPROCESSORS_ONLN
ncpus= sysconf(_SC_NPROCESSORS_ONLN); ncpus= sysconf(_SC_NPROCESSORS_ONLN);
#elif defined(__WIN__) #elif defined(__WIN__)
SYSTEM_INFO sysinfo; SYSTEM_INFO sysinfo;
/* /*
* We are not calling GetNativeSystemInfo here because (1) we We are not calling GetNativeSystemInfo here because (1) we
* don't believe that they return different values for number don't believe that they return different values for number
* of processors and (2) if WOW64 limits processors for Win32 of processors and (2) if WOW64 limits processors for Win32
* then we don't want to try to override that. then we don't want to try to override that.
*/ */
GetSystemInfo(&sysinfo); GetSystemInfo(&sysinfo);
ncpus= sysinfo.dwNumberOfProcessors; ncpus= sysinfo.dwNumberOfProcessors;
#else #else
/* unknown so play safe: assume SMP and forbid uniprocessor build */ /* Unknown so play safe: assume SMP and forbid uniprocessor build */
ncpus= 2; ncpus= 2;
#endif #endif
} }
#endif /* __linux__ || FreeBSD && HAVE_PTHREAD_GETAFFINITY_NP */
return ncpus; return ncpus;
} }
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment