Paya
Paya

Reputation: 5222

Changing process and thread processor affinity

Stopwatch has a bug on multiprocessor system:

On a multiprocessor computer, it does not matter which processor the thread runs on. However, because of bugs in the BIOS or the Hardware Abstraction Layer (HAL), you can get different timing results on different processors. To specify processor affinity for a thread, use the ProcessThread.ProcessorAffinity method.

I am trying to work around that by binding a dedicated thread to a particular processor. So, let's say there are 4 processors, the current process is bound to processor 1 and 2. My code binds the thread to processor 1. But what happens when the user then binds my process to run only on processor 2 and 3? What happens to the thread that I bound to processor 1?

I tried to look into the SetThreadAffinityMask and SetProcessAffinityMask Win32 APIs (as well as the .NET Process.ProcessorAffinity and ProcessThread.ProcessorAffinity) but there is no description about this particular situation. And for some reason, there is also no GetThreadAffinityMask API....

Upvotes: 1

Views: 642

Answers (1)

David Heffernan
David Heffernan

Reputation: 613013

The system won't let you specify an affinity that stops a thread from running.

  • If you try to specify an empty mask, then the API call fails.
  • If you try to set a thread mask that is not a subset of the process mask, then the API call fails.
  • If you set the thread mask first, and then set the process affinity to be disjoint to the thread affinity, the system will change the thread affinity to be the same as the process affinity.

So, in short, you have nothing to worry about. However you try to set affinities so that a thread is blocked, the system prevents it happening.

In order to read the thread affinity mask, you must call SetThreadAffinityMask which returns the previous mask.

Upvotes: 2

Related Questions