Win32: Atomic Execution of Code Block

天涯浪子 提交于 2019-12-24 10:38:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!