Joe Duffy (author of Parallel Programming on Windows ) writes in this blog article that Thread.Sleep (1) is preferred over Thread.Sleep (0) because it will pause for threads with one or lower priority. and not just equal priority threads, as for Thread.Sleep (0).
. The MSDN NET version says that Thread.Sleep (0) is special, it pauses this thread and allows other pending threads to execute. But it does not say anything about Thread.Sleep (1) (for any version of .NET).
So, does Thread.Sleep (1) really do something special?
Background:
I am updating my knowledge of parallel programming. I wrote C # code to illustrate that the pre / post increments and decrements are not atomic and therefore are not thread safe.
To avoid the need to create hundreds of threads, I put Thread.Sleep (0) after increasing the shared variable to force the scheduler to start another thread. This regular replacement of flows makes the non-atomic nature before / after increment / decrease more obvious.
Thread.Sleep (0) does not seem to cause additional delay, as expected. However, if I changed this to Thread.Sleep (1), it seems to return to normal sleep mode (for example, I get about a minimum of 1 ms delay).
This will mean that although Thread.Sleep (1) might be preferable, any code that uses it in a loop will run much slower.
This SO question is "Can someone explain this interesting behavior with Sleep (1)?" is kind of relevant, but it focuses on C ++ and just repeats the tutorial in Joe Daffy's blog post.
Here is my code for anyone interested (copied from LinqPad, so you might need to add a class around it):
int x = 0; void Main() { List<Thread> threadList=new List<Thread>(); Stopwatch sw=new Stopwatch(); for(int i=0; i<20; i++) { threadList.Add(new Thread(Go)); threadList[i].Priority=ThreadPriority.Lowest; } sw.Start(); foreach (Thread thread in threadList) { thread.Start(); } foreach (Thread thread in threadList) { thread.Join(); } sw.Stop(); Console.WriteLine(sw.ElapsedMilliseconds); Thread.Sleep(200); Console.WriteLine(x); } void Go() { for(int i=0;i<10000;i++) { x++; Thread.Sleep(0); } }
multithreading c #
Ash May 16 '13 at 9:58 a.m. 2013-05-16 09:58
source share