1
0
Fork 0
mirror of https://git.tukaani.org/xz.git synced 2024-04-04 12:36:23 +02:00
xz-archive/src/common/cpucores.h
Lasse Collin 60ccb80c9c Use sysctl() != -1 instead of !sysctl() to check if
the function call succeeded.

NetBSD 4.0 returns positive values on success, but
NetBSD Current and FreeBSD return zero. OpenBSD's
man page doesn't tell what sysctl() returns on
success. All these BSDs return -1 on error.

Thanks to Robert Elz and Thomas Klausner.
2009-09-05 01:20:29 +03:00

51 lines
1.1 KiB
C

///////////////////////////////////////////////////////////////////////////////
//
/// \file cpucores.h
/// \brief Get the number of online CPU cores
//
// Author: Lasse Collin
//
// This file has been put into the public domain.
// You can do whatever you want with this file.
//
///////////////////////////////////////////////////////////////////////////////
#ifndef CPUCORES_H
#define CPUCORES_H
#if defined(HAVE_CPUCORES_SYSCONF)
# include <unistd.h>
#elif defined(HAVE_CPUCORES_SYSCTL)
# ifdef HAVE_SYS_PARAM_H
# include <sys/param.h>
# endif
# ifdef HAVE_SYS_SYSCTL_H
# include <sys/sysctl.h>
# endif
#endif
static inline uint32_t
cpucores(void)
{
uint32_t ret = 0;
#if defined(HAVE_CPUCORES_SYSCONF)
const long cpus = sysconf(_SC_NPROCESSORS_ONLN);
if (cpus > 0)
ret = (uint32_t)(cpus);
#elif defined(HAVE_CPUCORES_SYSCTL)
int name[2] = { CTL_HW, HW_NCPU };
int cpus;
size_t cpus_size = sizeof(cpus);
if (sysctl(name, 2, &cpus, &cpus_size, NULL, 0) != -1
&& cpus_size == sizeof(cpus) && cpus > 0)
ret = (uint32_t)(cpus);
#endif
return ret;
}
#endif