]> granicus.if.org Git - python/commitdiff
Issue #10332: multiprocessing: fix a race condition when a Pool is closed
authorCharles-François Natali <neologix@free.fr>
Mon, 24 Oct 2011 16:45:29 +0000 (18:45 +0200)
committerCharles-François Natali <neologix@free.fr>
Mon, 24 Oct 2011 16:45:29 +0000 (18:45 +0200)
before all tasks have completed.

Lib/multiprocessing/pool.py
Lib/test/test_multiprocessing.py
Misc/NEWS

index e450319d4f4cdaa7dfb17b150b02e6c48b761669..04e7c447d17b4eff9fb043da6cbf485dc5fa37a6 100644 (file)
@@ -321,7 +321,11 @@ class Pool(object):
 
     @staticmethod
     def _handle_workers(pool):
-        while pool._worker_handler._state == RUN and pool._state == RUN:
+        thread = threading.current_thread()
+
+        # Keep maintaining workers until the cache gets drained, unless the pool
+        # is terminated.
+        while thread._state == RUN or (pool._cache and thread._state != TERMINATE):
             pool._maintain_pool()
             time.sleep(0.1)
         # send sentinel to stop workers
index 6940d0e2f7ef40129fcbd88b863a037a10a7f4e6..45bf4549feeca0cc8e63a1e9b16b007242936529 100644 (file)
@@ -1217,6 +1217,20 @@ class _TestPoolWorkerLifetime(BaseTestCase):
         p.close()
         p.join()
 
+    def test_pool_worker_lifetime_early_close(self):
+        # Issue #10332: closing a pool whose workers have limited lifetimes
+        # before all the tasks completed would make join() hang.
+        p = multiprocessing.Pool(3, maxtasksperchild=1)
+        results = []
+        for i in range(6):
+            results.append(p.apply_async(sqr, (i, 0.3)))
+        p.close()
+        p.join()
+        # check the results
+        for (j, res) in enumerate(results):
+            self.assertEqual(res.get(), sqr(j))
+
+
 #
 # Test that manager has expected number of shared objects left
 #
index 3909420e12e118fc784b2c5fb7ff34f6adf5159d..f7a741a32aadffac7db3ed4170b1a83a8032e30e 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -58,6 +58,9 @@ Core and Builtins
 Library
 -------
 
+- Issue #10332: multiprocessing: fix a race condition when a Pool is closed
+  before all tasks have completed.
+
 - Issue #13255: wrong docstrings in array module.
 
 - Issue #9168: now smtpd is able to bind privileged port.