How can you find the processor number a thread is running on?

Patrick Niedzielski picture Patrick Niedzielski · Feb 6, 2010 · Viewed 11.1k times · Source

I have a memory heap manager which partitions the heap into different segments based on the number of processors on the system. Memory can only be allocated on the partition that goes with the currently running thread's processor. This will help allow different processors to continue running even if two different ones want to allocate memory at the same time, at least I believe.

I have found the function GetCurrentProcessorNumber() for Windows, but this only works on Windows Vista and later. Is there a method that works on Windows XP?

Also, can this be done with pthreads on a POSIX system?

Answer

Ilia K. picture Ilia K. · Feb 7, 2010

From output of man sched_getcpu:

NAME
       sched_getcpu - determine CPU on which the calling thread is running

SYNOPSIS
       #define _GNU_SOURCE
       #include <utmpx.h>

       int sched_getcpu(void);

DESCRIPTION
   sched_getcpu() returns the number of the CPU
   on which the calling thread is currently executing.

RETURN VALUE
   On success, sched_getcpu() returns a non-negative CPU number.
   On error, -1 is returned and errno is set to indicate the error.

SEE ALSO
   getcpu(2)

Unfortunately, this is Linux specific. I doubt there is a portable way to do this.