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

前端 未结 5 1970
清酒与你
清酒与你 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:12

    What thread.sleep(0) is to free the cpu to handle other threads, but that doesn't mean that another thread couldn't be the current one. If you're trying to send the context to another thread, try to use some sort of signal.

    0 讨论(0)
  • 2021-01-17 20:16

    You should (almost) never abort threads. The best practice is to signal them to die (commit suicide).

    This is normally accomplished by setting some boolean variable and the threads should inspect its value to whether continue or not its execution.

    You are setting a string variable named "s". You will incur in race conditions. String is not thread safe. You can wrap the operations that manipulate it in a lock or use a built-in type that is thread-safe.

    Always pay attention, in the documentation, to know if the types you use are thread-safe.

    Because of this you can't rely on your results because your program is not thread-safe. If you run the program several times my guess is that you'll get different outputs.

    Note: When using a boolean to share some state to cancel threads, make sure it is marked as volatile. JIT might optimize the code and never looks at its changed value.

    0 讨论(0)
  • 2021-01-17 20:18

    The next thread the processor handles is random thread and it even could be the same thread you just called Thread.Sleep(0). To ensure that next thread will be not the same thread you can call Thread.Yield() and check it's return result - if os has another thread that can run true will be returned else false.

    0 讨论(0)
  • 2021-01-17 20:21

    If you'd expand the width of the console to be 5 time larger than current then you'd see what you expect, lines not reaching the console width. The problem is one time slice is actually very long. So, to have the expected effect with normal console with you'd have to slow down the Points thread, but without using Sleep. Instead of while (true) loop try this

    for (int i = 0;; i++)
    {
      if (int % 10 == 0)
        s += ".";
    }
    

    To slow down the thread even more replace number 10 with bigger number.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题