]> granicus.if.org Git - python/commitdiff
Issue #14406: Fix a race condition when using `concurrent.futures.wait(return_when...
authorAntoine Pitrou <solipsis@pitrou.net>
Sat, 31 Mar 2012 18:23:30 +0000 (20:23 +0200)
committerAntoine Pitrou <solipsis@pitrou.net>
Sat, 31 Mar 2012 18:23:30 +0000 (20:23 +0200)
Patch by Matt Joiner.

Lib/concurrent/futures/_base.py
Lib/test/test_concurrent_futures.py
Misc/NEWS

index 79b91d495fca987366c9b64a952e361a4e49a0d5..9f11f6977f1dd6a850505c273972b66ad1457c59 100644 (file)
@@ -112,12 +112,14 @@ class _AllCompletedWaiter(_Waiter):
     def __init__(self, num_pending_calls, stop_on_exception):
         self.num_pending_calls = num_pending_calls
         self.stop_on_exception = stop_on_exception
+        self.lock = threading.Lock()
         super().__init__()
 
     def _decrement_pending_calls(self):
-        self.num_pending_calls -= 1
-        if not self.num_pending_calls:
-            self.event.set()
+        with self.lock:
+            self.num_pending_calls -= 1
+            if not self.num_pending_calls:
+                self.event.set()
 
     def add_result(self, future):
         super().add_result(future)
index 372da27dca398da0ba4c6827a4666e1356a2bcdc..2afa93802e2601728cb2126ff9546d4f59a0270a 100644 (file)
@@ -183,7 +183,9 @@ class ProcessPoolShutdownTest(ProcessPoolMixin, ExecutorShutdownTest):
         for p in processes:
             p.join()
 
+
 class WaitTests(unittest.TestCase):
+
     def test_first_completed(self):
         future1 = self.executor.submit(mul, 21, 2)
         future2 = self.executor.submit(time.sleep, 1.5)
@@ -284,7 +286,21 @@ class WaitTests(unittest.TestCase):
 
 
 class ThreadPoolWaitTests(ThreadPoolMixin, WaitTests):
-    pass
+
+    def test_pending_calls_race(self):
+        # Issue #14406: multi-threaded race condition when waiting on all
+        # futures.
+        event = threading.Event()
+        def future_func():
+            event.wait()
+        oldswitchinterval = sys.getswitchinterval()
+        sys.setswitchinterval(1e-6)
+        try:
+            fs = {self.executor.submit(future_func) for i in range(100)}
+            event.set()
+            futures.wait(fs, return_when=futures.ALL_COMPLETED)
+        finally:
+            sys.setswitchinterval(oldswitchinterval)
 
 
 class ProcessPoolWaitTests(ProcessPoolMixin, WaitTests):
index d084fac9b80d1af9524d65e137aff2cf97fa5329..d814b17ff9c72c7f210f09d57c2048698453be66 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -31,6 +31,9 @@ Core and Builtins
 Library
 -------
 
+- Issue #14406: Fix a race condition when using ``concurrent.futures.wait(
+  return_when=ALL_COMPLETED)``.  Patch by Matt Joiner.
+
 - Issue #14409: IDLE now properly executes commands in the Shell window
   when it cannot read the normal config files on startup and
   has to use the built-in default key bindings.