Count the number of CPU cores using pthread_setaffinity_np

86 views Asked by At

Just trying to devise an experimental method to count the number of CPU cores available on a system by setting the thread affinity for each core until it reaches an error (EINVAL "Invalid argument"). Definitely not recommended for production systems!

The method seems to work but are there any obvious pitfalls or reliability issues?

cpu.c

#define _GNU_SOURCE
#include <pthread.h>
#include <sched.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>

int GetNumberCPUs_Experimental() {
    cpu_set_t cpuset;
    int cores = 0, max_cores = 1024;

    for (; cores < max_cores; cores++) {
        CPU_ZERO(&cpuset);
        CPU_SET(cores, &cpuset);
        if (pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpuset) == EINVAL) break;
    }
    return cores;
}

int main() {
    printf("CPU(s): %ld\n", sysconf(_SC_NPROCESSORS_ONLN));
    printf("CPU(s): %d (Experimental)\n", GetNumberCPUs_Experimental());
    return 0;
}

cpu

0

There are 0 answers