Is there a function or any other way to know, programatically, what core of what processor a given thread of my program (pid) is running on? Both OpenMP or Pthreads solutions would help me, if possible. Thanks.
-
2possible duplicate of [How can I get the CPU core number from within a user-space app (Linux, C)?](http://stackoverflow.com/questions/491520/how-can-i-get-the-cpu-core-number-from-within-a-user-space-app-linux-c) – John Zwinck Apr 28 '11 at 13:52
-
The OpenMP API doesn't give the user a method to find out this information. You might be able to get it by calling whatever the OpenMP implementation is based on. However, as already mentioned, that really isn't of much help unless the OpenMP threads are bound to a specific processor (in which case you don't need to ask). Otherwise, the OS can change the processor the OpenMP thread is using anytime it wants to. Why do you want that information? – ejd Apr 28 '11 at 14:07
-
Why? This usually means you're looking at threads the wrong way... – R.. GitHub STOP HELPING ICE Apr 28 '11 at 15:02
4 Answers
This is going to be platform-specific, I would think. On Windows you can use NtGetCurrentProcessorNumber, but this is caveat-ed as possibly disappearing.
I expect this is hard to do, because there's nothing to stop the thread being moved to a new core at any time (in most apps, anyway). As soon as you get the result, it could be out of date.

- 53,498
- 9
- 91
- 140
For pthreads, I think sched_getaffinity()
is at least part of the solution. Not sure exactly how pthreads names the CPU:s and cores, though.

- 391,730
- 64
- 469
- 606
-
Thanks. The affinity may change though, right? Or once the thread with a given pid is created and is running won't change affinity? – Dervin Thunk Apr 28 '11 at 13:54
-
@Dervin AFAIK on linux if you bind your thread to a core it won't change. On windows there is no such thing as 'binding' to a core. You can indicate to the scheduler which core you'd like to use but there is no guarantee that the scheduler will use that core all the time. – RedX Apr 28 '11 at 14:09
-
2By default there is no affinity, and this will not tell you anything. Only if you've already set an affinity will it give you any information. – R.. GitHub STOP HELPING ICE Apr 28 '11 at 15:01
This is hard to do portably, as the answer depends both on hardware and OS.
The hardware locality library is a new tool which allows you to query CPU/core/thread etc information (and set affinity bindings) in an OS/hardware agnostic way. It supports a huge list of hardware and OSes, and so should add a lot of portability to these sorts of queries. Once you map out your system's topology, hwloc_get_last_cpu_location
will return the CPU the thread last ran on, where CPU can mean core or hardware thread.

- 50,107
- 9
- 127
- 158