问题
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
回答1:
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).
回答2:
I'm not so sure you can. Unless you know what the underlying operations are in each function, and since they happen to be Windows API calls... good luck.
Would it not be possible to just adjust for percentages over 100?
perc = ( perc > 100.0f ) ? 100.0f : perc;
回答3:
Sadly there is no way. In between two system calls in Win32 there is no way to prevent your process/thread from being context switched out. Otherwise it would be trivial for someone to implement a process that locked down the system by refusing to every get switched out.
回答4:
Would calling the functions in the opposite order help? (99% is better than 101%...)
Also if you force a context switch just before doing this (for instance by calling Sleep()), you will probably reduce the chances of getting switched out. I don't know how well that would work though.
来源:https://stackoverflow.com/questions/288364/win32-atomic-execution-of-code-block