InitializeCriticalSectionAndSpinCount optimal SpinCount (user mode)

蓝咒 提交于 2019-12-06 04:35:52

What the documentation actually says, with my emphasis on the text that you removed, is:

You can improve performance significantly by choosing a small spin count for a critical section of short duration.

So, the choice of spin count depends very critically on the duration of the critical section.

You ask:

However, since waiting on a spinner is faster than waiting for an object, doesn't it make sense to have the SpinCount as high as possible?

It is simply not true that spinning is faster than blocking. For a long duration critical section, it is best to avoid spinning altogether. If it is likely that the lock won't be released for a significant amount of time, then the best policy is to block immediately and wait until you can acquire the lock. Even for a short duration section, it is possible that the thread that holds the lock is not scheduled to run, in which case spinning is clearly wasteful of CPU resource.

Spinning is only beneficial if there is a good probability that the lock can be acquired whilst spinning. And even then only if the time spent spinning is less than the time spent yielding, the context switch cost.

I agree to the statement "You can improve performance significantly by choosing a small spin count" itself.

When I tested my object pool class which uses InitializeCriticalSectionAndSpinCount on a 8-core PC, the best value was lesser than 20. The larger spin count is, the slower it works.

These are my deduction by this test result:

  • The smaller spin count is, the lesser meaningless processing is consumed.
  • Very small spin count works well for routines where O(1) is guaranteed (e.g. no loop)

I don't think spin count should be larger than thousands. Spin count is a busy-wait. It not only consumes CPU power, but also consumes much bandwidth between CPU and RAM, thus it may cause starvation of traffic between other CPUs and RAM.

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