Search code examples
winapiatomiccontext-switch

Win32: Atomic Execution of Code Block


I have two system calls GetSystemTime() and GetThreadTimes() that I need to calculate the CPU utilization by a given Win32 thread.

For the sake of accuracy, I need to ensure that both GetSystemTime() and GetThreadTimes() are executed atomically; i.e. there should be no context switch in between a call to GetSystemTime() & GetThreadTimes().

The reason is that occasionally I end up with a percentage of over 100% (~ 1 in 500).

How can I ensure an atomic execution of the 2 function calls?

Thanks, Sachin


Solution

  • Your best bet would be assigning computing thread a realtime priority. Realtime threads only get preempted by other realtime threads (or ones boosted to realtime priority).