Add a SpinWait step when waiting on a task. Fix 100% CPU bother.
authorJérémie Laval <jeremie.laval@gmail.com>
Thu, 29 Jul 2010 09:10:31 +0000 (11:10 +0200)
committerJérémie Laval <jeremie.laval@gmail.com>
Thu, 29 Jul 2010 09:49:58 +0000 (11:49 +0200)
After some time the call to SpinWait.SpinOnce will fall back to the more stalling Thread.Sleep (1) call.

mcs/class/corlib/System.Threading.Tasks/Internal/ThreadWorker.cs

index f16a05d907c4556e71c522a6e975255a3dc8fa91..e44d03d37cf0ef330b087891611b7e2d2ce28aa6 100644 (file)
@@ -212,6 +212,8 @@ namespace System.Threading.Tasks
                public static void WorkerMethod (Func<bool> predicate, IProducerConsumerCollection<Task> sharedWorkQueue,
                                                 ThreadWorker[] others)
                {
+                       SpinWait wait = new SpinWait ();
+
                        while (!predicate ()) {
                                Task value;
                                
@@ -226,9 +228,8 @@ namespace System.Threading.Tasks
                                }
                                
                                // First check to see if we comply to predicate
-                               if (predicate ()) {
+                               if (predicate ())
                                        return;
-                               }
                                
                                // Try to complete other work by stealing since our desired tasks may be in other worker
                                ThreadWorker other;
@@ -245,10 +246,11 @@ namespace System.Threading.Tasks
                                                }
                                        }
                                        
-                                       if (predicate ()) {
+                                       if (predicate ())
                                                return;
-                                       }
                                }
+
+                               wait.SpinOnce ();
                        }
                }