Thread.Sleep(0) doesn't work as described?

前端 未结 5 1973
清酒与你
清酒与你 2021-01-17 19:49

I am currently reading this excellent article on threading and read the following text:

Thread.Sleep(0) relinquishes the thread’s current time slice i

5条回答
  •  终归单人心
    2021-01-17 20:27

    If you have access to a machine (or perhaps a VM) with only a single core/processor, try running your code on that machine. You may be surprised with how the results vary. Just because two threads refer to the same variable "s", does not mean they actually refer to the same value at the same time, due to various levels of caching that can occur on modern multi-core (and even just parallel pipeline) CPUs. If you want to see how the yielding works irrespective of the caching issues, try wrapping each s += expression inside a lock statement.

提交回复
热议问题