diff Implab/Parallels/DispatchPool.cs @ 30:2fad2d1f4b03

small refactoring, cleanup.
author cin
date Mon, 07 Apr 2014 03:25:57 +0400
parents ee04e1fa78da
children dabf79fde388
line wrap: on
line diff
--- a/Implab/Parallels/DispatchPool.cs	Thu Mar 06 17:59:03 2014 +0400
+++ b/Implab/Parallels/DispatchPool.cs	Mon Apr 07 03:25:57 2014 +0400
@@ -143,18 +143,24 @@
                 // anyway it may take some time for the thread to start
                 // we will ensure that at least one thread is running
 
-                if (AllocateThreadSlot(1)) {
-                    // if there were no threads in the pool
-                    var worker = new Thread(this.Worker);
-                    worker.IsBackground = true;
-                    worker.Start();
-                }
+                EnsurePoolIsAlive();
             } else {
                 // if there is no sleeping threads in the pool
-                if (!StartWorker())
-                    // we haven't started a new thread, but the current can be on the way and it can't process the queue
+                if (!StartWorker()) {
+                    // we haven't started a new thread, but the current can be on the way to terminate and it can't process the queue
                     // send it a signal to spin again
-                    SignalThread(); 
+                    SignalThread();
+                    EnsurePoolIsAlive();
+                }
+            }
+        }
+
+        private void EnsurePoolIsAlive() {
+            if (AllocateThreadSlot(1)) {
+                // if there were no threads in the pool
+                var worker = new Thread(this.Worker);
+                worker.IsBackground = true;
+                worker.Start();
             }
         }
 
@@ -177,12 +183,9 @@
                 // in case at the moment the last thread was being released
                 // a new task was added to the queue, we need to try
                 // to revoke the thread to avoid the situation when the task is left unprocessed
-                if (last && Sleep(0)) { // Sleep(0) will fetch pending task or will return false
-                    if (AllocateThreadSlot(1))
-                        return true; // spin again...
-                    else
-                        SignalThread(); // since Sleep(0) has fetched the signal we neet to reschedule it
-                    
+                if (last && FetchSignalOrWait(0)) { // FetchSignalOrWait(0) will fetch pending task or will return false
+                    SignalThread(); // since FetchSignalOrWait(0) has fetched the signal we need to reschedule it
+                    return AllocateThreadSlot(1); // ensure that at least one thread is alive
                 }
 
                 return false;