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

Skip to content

Commit 799d25c

Browse files
committed
pythongh-94440: Fix issue of ProcessPoolExecutor shutdown hanging
1 parent 62bb7a3 commit 799d25c

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

Lib/concurrent/futures/process.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -364,6 +364,11 @@ def run(self):
364364
if self.is_shutting_down():
365365
self.flag_executor_shutting_down()
366366

367+
# If only canceled futures remain in pending_work_items, we
368+
# should purge them now to avoid waiting forever in our
369+
# subsequent call to wait_result_broken_or_wakeup.
370+
self.add_call_item_to_queue()
371+
367372
# Since no new work items can be added, it is safe to shutdown
368373
# this thread if there are no pending work items.
369374
if not self.pending_work_items:

Lib/test/test_concurrent_futures.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
from logging.handlers import QueueHandler
1515
import os
1616
import queue
17+
import signal
1718
import sys
1819
import threading
1920
import time
@@ -397,6 +398,33 @@ def test_hang_gh83386(self):
397398
self.assertFalse(err)
398399
self.assertEqual(out.strip(), b"apple")
399400

401+
def test_hang_gh94440(self):
402+
"""shutdown(wait=True) doesn't hang when a future was submitted and
403+
quickly canceled right before shutdown.
404+
405+
See https://github.com/python/cpython/issues/94440.
406+
"""
407+
if not hasattr(signal, 'alarm'):
408+
raise unittest.SkipTest(
409+
"Tested platform does not support the alarm signal")
410+
411+
def timeout(_signum, _frame):
412+
raise RuntimeError("timed out waiting for shutdown")
413+
414+
kwargs = {}
415+
if getattr(self, 'ctx', None):
416+
kwargs['mp_context'] = self.get_context()
417+
executor = self.executor_type(max_workers=1, **kwargs)
418+
executor.submit(int).result()
419+
old_handler = signal.signal(signal.SIGALRM, timeout)
420+
try:
421+
signal.alarm(5)
422+
executor.submit(int).cancel()
423+
executor.shutdown(wait=True)
424+
finally:
425+
signal.alarm(0)
426+
signal.signal(signal.SIGALRM, old_handler)
427+
400428

401429
class ThreadPoolShutdownTest(ThreadPoolMixin, ExecutorShutdownTest, BaseTestCase):
402430
def test_threads_terminate(self):

0 commit comments

Comments
 (0)