views:

228

answers:

3

Is there a Windows API or any way to determine on which physical processor/core my current thread runs? I don't need that information. I'm just curious.

Edit: I'm not interested in the processors the thread is allowed to run on. I would like to know on exactly which one it currently runs. I know that the threads switch pretty fast from one to another...

+1  A: 

For controlling which processor your process or thread runs on using the Windows API you can use SetThreadAffinityMask or SetProcessAffinityMask.

These work by setting bits in a bit mask, where each bit represents a processor your thread or process can be scheduled for:

BOOL WINAPI SetProcessAffinityMask(
  __in  HANDLE hProcess,
  __in  DWORD_PTR dwProcessAffinityMask
);

Call GetProcessAffinityMask to discover which processors are available for use in these calls.

Simon Steele
+2  A: 

You can query the processor affinity with GetProcessAffinityMask. If you haven't set processor affinity, I'm unsure how useful the result will be though, as the thread can flit between processors.

Rowland Shaw
+3  A: 

Threads will often switch from processor to processor, so it's kind of meaningless, but you can use GetCurrentProcessorNumber

As others have said, you can use GetProcessAffinityMask or GetThreadIdealProcessor, but those will only work if you've already set an affinity mask or ideal processor for the thread.

Eric Petroelje
Didn't think this was possible, but turns out that it is - edited my answer to reflect that.
Eric Petroelje
Nice, didn't realise that was possible.
Simon Steele
I could do some cool useless things with that information like statistics or some kind of visualization ;) Thanks
iik