At first, I figured that there might be a Win32 function to do this. So, I looked around unsuccessfully in MSDN hoping for a "get" equivalent of SetThreadAffinityMask or SetThreadIdealProcessor.
It turns out the correct way to find this information is to ask the processor. Seems logical if you think about it, but unfortunately the answer not easily googleable because of the weird terminology!
After a little digging around, I found that the CPUID instruction has this interesting beast called an APIC ID. Intel documentation says:
"Each logical processor has a unique APIC ID,which is initially assigned by the hardware at system reset and can be later reprogrammed by the BIOS or the operating system. On a processor that supports Hyper-Threading Technology, the CPUID instruction also provides the initial APIC ID for a logical processor prior to any changes by the BIOS or operating system."Simplified, this just means that in a multi-processor/multi-core system, the APIC ID is a unique identifier for each logical processor.
What's a logical processor? A hyperthreaded system capable of running two threads "in parallel" has two logical processors. A quad-core system has 4 logical processors. A simple way of looking at this is that you have as many logical processors as graphs in the performance tab of the task manager!
So, all you have to do is use the CPUID function 0x0001 and look in bits 31-24 of the EBX register, which is where the APIC ID lives. This looks like this:
int apic_id;
__asm
{
mov eax, 1;
cpuid;
shr ebx, 24;
mov apic_id, ebx;
}
So that's that!
Let me know if you have questions/comments.
1 comments:
a very interesting post on a topic i have found little to no coverage on. im not big on asm, but am assuning this method could only be used to find the core the current thread is running on, as a pposed to any particular, or specified, thread. I am trying to write a more detailed windows task manager, as a base app for some experimentation. I need some way of determining which core/logical processor any given thread is running on...
Post a Comment