On Win32, how do you move a thread to another CPU core?

I would like to make sure that the thread is moved to a specific CPU core and can never be transferred from it by the scheduler.

There is a call to SetThreadAffinityMask() , but no GetThreadAffinityMask() .

The reason I need this is because the high resolution timers will be mixed up if the scheduler moves this thread to another CPU.

+6
c ++ c multithreading winapi multicore
source share
4 answers

You should probably just use SetThreadAffinityMask and trust that it works.

MSDN

+9
source share

If you can call a function that returns a number indicating which processor the thread is running on without using proximity, the answer is often erroneous as soon as the function returns. Thus, checking the mask returned by SetThreadAffinityMask() as close as possible, outside the kernel code, working on increased IRQL, and even if the change .

It looks like you are trying to get around t21 watch problems. If you use the RDTSC statement directly, call QueryPerformanceCounter() instead:

  • QueryPerformanceCounter() in Windows Vista uses HPET if it is supported by the chipset and is located in the ACPI system tables.
  • AMD-based systems that use the AMD Processor Driver will mostly compensate for skewed multi-core clocks if you call QueryPerformanceCounter() , but this does nothing for applications that use RDTSC directly. AMD Dual-Core Optimizer is a hack for applications that use RDTSC directly, but if the number of clock skews changes due to C1 (when the clock speed decreases in C1 power state), you will still have clock distortion. And these utilities are probably not very common, so using affinity with QueryPerformanceCounter() is still a good idea.
+4
source share

What did Ken say. But if you do not trust it to work, you can call SetThreadAffinityMask again and confirm that the return value matches the expected mask. (But then, of course, if you do not trust the function, then you cannot trust the second call ...)

Do not confuse the existence of GetProcessAffinityMask. This function does not exist to test the operation of SetProcessAffinityMask, but, for example, therefore, you can build a thread affinity, which is a subset of the affinity for the process.

Just look at the return value and make sure it is not 0, and you should be fine.

+3
source share

No need for Get Thread AffinityMask. Just get the Get Process AffinityMask value, turn off a few bits, then call SetThreadAffinityMask. Threads inherit the affinity mask of the process, and since their attachment is under your control, you already know the thread merge mask (this is the one you set it to).

+1
source share

All Articles