0
votes

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....

1
These was a problem in the very early days of multi-processor machines. Those HAL and BIOS bugs were solved over a decade ago. Are you just imagining you have a problem or did you actually verify it? - Hans Passant
@HansPassant stackoverflow.com/questions/1008345/… The bug is related to running the software on a virtual machine - Paya
@DavidHeffernan I will not. As stated in the question, my worry is that someone else is going to. And it's not clear what the thread affinity is going to be after changing the process affinity. - Paya
@DavidHeffernan the problem is that i tend to write resilient software and i don't like it to fall apart when the user messes up with "seemingly innocent processor affinity" - which you can do from stock task manager. - Paya
@DavidHeffernan the problem is to safely and reliably use Stopwatch in heavily multithreaded concurrent environment under any circumstances (including while running in VM). - Paya

1 Answers

1
votes

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.