Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit f8859e1

Browse files
author
Charles-François Natali
committed
Issue #10332: multiprocessing: fix a race condition when a Pool is closed
before all tasks have completed.
1 parent d6ca6c2 commit f8859e1

3 files changed

Lines changed: 22 additions & 1 deletion

File tree

Lib/multiprocessing/pool.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -321,7 +321,11 @@ def map_async(self, func, iterable, chunksize=None, callback=None,
321321

322322
@staticmethod
323323
def _handle_workers(pool):
324-
while pool._worker_handler._state == RUN and pool._state == RUN:
324+
thread = threading.current_thread()
325+
326+
# Keep maintaining workers until the cache gets drained, unless the pool
327+
# is terminated.
328+
while thread._state == RUN or (pool._cache and thread._state != TERMINATE):
325329
pool._maintain_pool()
326330
time.sleep(0.1)
327331
# send sentinel to stop workers

Lib/test/test_multiprocessing.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1217,6 +1217,20 @@ def test_pool_worker_lifetime(self):
12171217
p.close()
12181218
p.join()
12191219

1220+
def test_pool_worker_lifetime_early_close(self):
1221+
# Issue #10332: closing a pool whose workers have limited lifetimes
1222+
# before all the tasks completed would make join() hang.
1223+
p = multiprocessing.Pool(3, maxtasksperchild=1)
1224+
results = []
1225+
for i in range(6):
1226+
results.append(p.apply_async(sqr, (i, 0.3)))
1227+
p.close()
1228+
p.join()
1229+
# check the results
1230+
for (j, res) in enumerate(results):
1231+
self.assertEqual(res.get(), sqr(j))
1232+
1233+
12201234
#
12211235
# Test that manager has expected number of shared objects left
12221236
#

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,9 @@ Core and Builtins
5858
Library
5959
-------
6060

61+
- Issue #10332: multiprocessing: fix a race condition when a Pool is closed
62+
before all tasks have completed.
63+
6164
- Issue #13255: wrong docstrings in array module.
6265

6366
- Issue #9168: now smtpd is able to bind privileged port.

0 commit comments

Comments
 (0)