SwitchToThread/Thread.Yield vs. Thread.Sleep(0) vs. Thead.Sleep(1)

后端 未结 4 1441
-上瘾入骨i
-上瘾入骨i 2020-12-13 04:25

I am trying to write the ultimate \"Yield\" method to yield the current time slice to other threads. So far I have found that there are several different ways to make the th

4条回答
  •  生来不讨喜
    2020-12-13 04:39

    SpinWait is useful on hyperthreaded processors. With hyperthreading, multiple OS scheduled threads can be running on the same physical processor, sharing the processor resources. SpinWait indicates to the processor that you are not doing any useful work and that it should run code from a different logical CPU. As the name suggests, it is typically used when you are spinning.

    Suppose you have code like:

    while (!foo) {} // Spin until foo is set.
    

    If this thread is running on a thread on a hyperthreaded processor, it is consuming processor resources that could be used for other threads running on the processor.

    By changing to:

    while (!foo) {Thread.SpinWait(1);} 
    

    We are indicating to the CPU to give some resources to the other thread.

    SpinWait does not affect OS scheduling of threads.

    For your main questions about the "Ultimate Yield", it depends heavily on your situation - you won't be able to get a good answer without clarifying why you want a thread to yield. From my perspective, the best way to yield the processor is getting the thread to enter a wait state and only waking when there is work to do. Anything else is just wasting CPU time.

提交回复
热议问题