Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions Doc/library/multiprocessing.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2635,6 +2635,11 @@ with the :class:`Pool` class.
:exc:`multiprocessing.TimeoutError` is raised. If the remote call raised
an exception then that exception will be reraised by :meth:`get`.

.. versionchanged:: 3.16
If the call is abandoned when the pool is terminated, the result
becomes ready and :meth:`get` raises :exc:`RuntimeError`.
Neither callback is invoked for this result.

.. method:: wait([timeout])

Wait until the result is available or until *timeout* seconds pass.
Expand Down
75 changes: 67 additions & 8 deletions Lib/multiprocessing/pool.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,8 +156,54 @@ class _PoolCache(dict):
"""
def __init__(self, /, *args, notifier=None, **kwds):
self.notifier = notifier
self._async_lock = threading.Lock()
self._accept_async_results = True
self._publishing = {}
super().__init__(*args, **kwds)

def register_async_result(self, result):
with self._async_lock:
if not self._accept_async_results:
raise ValueError("Pool not running")
self[result._job] = result

def cancel_async_results(self):
with self._async_lock:
self._accept_async_results = False
abandoned = [
self.pop(job)
for job, result in self.copy().items()
if isinstance(result, ApplyResult) and job not in self._publishing
]
for result in abandoned:
result._cancel()

def publish(self, job, index, value):
with self._async_lock:
result = self[job]
is_async = isinstance(result, ApplyResult)
if is_async:
if not self._accept_async_results:
return
self._publishing[job] = self._publishing.get(job, 0) + 1
try:
result._set(index, value)
finally:
if is_async:
self._finish_publication(job)

def _finish_publication(self, job):
abandoned = None
with self._async_lock:
self._publishing[job] -= 1
if self._publishing[job] == 0:
del self._publishing[job]
if not self._accept_async_results:
# An interrupted map may still have outstanding chunks.
abandoned = self.pop(job, None)
if abandoned is not None:
abandoned._cancel()

def __delitem__(self, item):
super().__delitem__(item)

Expand Down Expand Up @@ -438,6 +484,7 @@ def apply_async(self, func, args=(), kwds={}, callback=None,
'''
self._check_running()
result = ApplyResult(self, callback, error_callback)
self._cache.register_async_result(result)
self._taskqueue.put(([(result._job, 0, func, args, kwds)], None))
return result

Expand Down Expand Up @@ -468,6 +515,8 @@ def _map_async(self, func, iterable, mapper, chunksize=None, callback=None,
task_batches = Pool._get_tasks(func, iterable, chunksize)
result = MapResult(self, chunksize, len(iterable), callback,
error_callback=error_callback)
if result._number_left:
self._cache.register_async_result(result)
self._taskqueue.put(
(
self._guarded_task_generation(result._job,
Expand Down Expand Up @@ -557,7 +606,7 @@ def _handle_tasks(taskqueue, put, outqueue, pool, cache):
except Exception as e:
job, idx = task[:2]
try:
cache[job]._set(idx, (False, e))
cache.publish(job, idx, (False, e))
except KeyError:
pass
else:
Expand Down Expand Up @@ -608,7 +657,7 @@ def _handle_results(outqueue, get, cache):

job, i, obj = task
try:
cache[job]._set(i, obj)
cache.publish(job, i, obj)
except KeyError:
pass
task = job = obj = None
Expand All @@ -625,7 +674,7 @@ def _handle_results(outqueue, get, cache):
continue
job, i, obj = task
try:
cache[job]._set(i, obj)
cache.publish(job, i, obj)
except KeyError:
pass
task = job = obj = None
Expand Down Expand Up @@ -711,6 +760,11 @@ def _terminate_pool(cls, taskqueue, inqueue, outqueue, pool, change_notifier,
change_notifier.put(None)

task_handler._state = TERMINATE

# A callback may be waiting for another result. Settle abandoned
# results before waiting for any handler to finish.
cache.cancel_async_results()

# Release all semaphores to wake up task_handler to stop.
for buffersize_sema in tuple(taskqueue_buffersize_semaphores):
buffersize_sema.release()
Expand All @@ -730,7 +784,8 @@ def _terminate_pool(cls, taskqueue, inqueue, outqueue, pool, change_notifier,
# We must wait for the worker handler to exit before terminating
# workers because we don't want workers to be restarted behind our back.
util.debug('joining worker handler')
if threading.current_thread() is not worker_handler:
current_thread = threading.current_thread()
if current_thread is not worker_handler:
worker_handler.join()

# Terminate workers which haven't already finished.
Expand All @@ -741,11 +796,11 @@ def _terminate_pool(cls, taskqueue, inqueue, outqueue, pool, change_notifier,
p.terminate()

util.debug('joining task handler')
if threading.current_thread() is not task_handler:
if current_thread is not task_handler:
task_handler.join()

util.debug('joining result handler')
if threading.current_thread() is not result_handler:
if current_thread is not result_handler:
result_handler.join()

if pool and hasattr(pool[0], 'terminate'):
Expand Down Expand Up @@ -786,7 +841,6 @@ def __init__(self, pool, callback, error_callback):
self._cache = pool._cache
self._callback = callback
self._error_callback = error_callback
self._cache[self._job] = self

def ready(self):
return self._event.is_set()
Expand All @@ -808,6 +862,12 @@ def get(self, timeout=None):
else:
raise self._value

def _cancel(self):
self._success = False
self._value = RuntimeError("Pool has been terminated")
self._pool = None
self._event.set()

def _set(self, i, obj):
self._success, self._value = obj
try:
Expand Down Expand Up @@ -849,7 +909,6 @@ def __init__(self, pool, chunksize, length, callback, error_callback):
if chunksize <= 0:
self._number_left = 0
self._event.set()
del self._cache[self._job]
else:
self._number_left = length//chunksize + bool(length % chunksize)

Expand Down
148 changes: 148 additions & 0 deletions Lib/test/_test_multiprocessing.py
Original file line number Diff line number Diff line change
Expand Up @@ -3516,6 +3516,154 @@ def raise_with_context(exc):
def unpickleable_result():
return lambda: 42

class _TestPoolTermination(BaseTestCase):
ALLOWED_TYPES = ('processes',)

@warnings_helper.ignore_fork_in_thread_deprecation_warnings()
def test_terminate_async_results(self):
callbacks = []
with self.Pool(1) as pool:
completed = pool.apply_async(sqr, (2,))
self.assertEqual(completed.get(support.SHORT_TIMEOUT), 4)

pending = pool.apply_async(
time.sleep, (support.LONG_TIMEOUT,),
callback=callbacks.append, error_callback=callbacks.append,
)
mapped = pool.map_async(
time.sleep, [support.LONG_TIMEOUT] * 2, chunksize=1,
callback=callbacks.append, error_callback=callbacks.append,
)
waiter_started = threading.Event()
waiter_outcome = pyqueue.SimpleQueue()
wait = pending.wait

def signal_and_wait(timeout):
waiter_started.set()
wait(timeout)

def get_pending():
try:
waiter_outcome.put(pending.get(support.SHORT_TIMEOUT))
except Exception as exc:
waiter_outcome.put(exc)

waiter = threading.Thread(target=get_pending)
with unittest.mock.patch.object(pending, 'wait', signal_and_wait):
with threading_helper.start_threads([waiter]):
self.assertTrue(waiter_started.wait(support.SHORT_TIMEOUT))
pool.terminate()

self.assertIsInstance(waiter_outcome.get_nowait(), RuntimeError)
for result in (pending, mapped):
with self.subTest(result=type(result)):
self.assertTrue(result.ready())
self.assertFalse(result.successful())
with self.assertRaisesRegex(RuntimeError, 'Pool has been terminated'):
result.get(0)
self.assertEqual(completed.get(0), 4)
self.assertTrue(completed.successful())
self.assertEqual(callbacks, [])

@warnings_helper.ignore_fork_in_thread_deprecation_warnings()
def test_terminate_from_result_callback(self):
submitted = threading.Event()
with self.Pool(1) as pool:
def terminate(_):
if not submitted.wait(support.SHORT_TIMEOUT):
raise AssertionError('The second job was not submitted')
pool.terminate()
with self.assertRaisesRegex(RuntimeError, 'Pool has been terminated'):
pending.get(0.25)

completed = pool.apply_async(sqr, (2,), callback=terminate)
try:
pending = pool.apply_async(time.sleep, (support.LONG_TIMEOUT,))
finally:
submitted.set()
self.assertEqual(completed.get(support.SHORT_TIMEOUT), 4)
pool.join()
with self.assertRaisesRegex(RuntimeError, 'Pool has been terminated'):
pending.get(0)

@warnings_helper.ignore_fork_in_thread_deprecation_warnings()
def test_terminate_while_result_callback_waits(self):
started = threading.Event()
joining = threading.Event()

with self.Pool(1) as pool:
result_handler_join = pool._result_handler.join

def join_result_handler():
joining.set()
result_handler_join()

def callback(_):
started.set()
self.assertTrue(joining.wait(support.SHORT_TIMEOUT))
pool.terminate()
with self.assertRaisesRegex(RuntimeError, 'Pool has been terminated'):
pending.get(0.5)

completed = pool.apply_async(sqr, (2,), callback=callback)
pending = pool.apply_async(time.sleep, (support.LONG_TIMEOUT,))
self.assertTrue(started.wait(support.SHORT_TIMEOUT))
with unittest.mock.patch.object(
pool._result_handler, 'join', join_result_handler
):
pool.terminate()

self.assertEqual(completed.get(0), 4)
self.assertTrue(pending.ready())

@warnings_helper.ignore_fork_in_thread_deprecation_warnings()
def test_terminate_during_map_result_publication(self):
from multiprocessing.pool import MapResult

publishing = threading.Event()
joining = threading.Event()
set_result = MapResult._set

def publish_chunk(result, index, value):
publishing.set()
if not joining.wait(support.SHORT_TIMEOUT):
raise AssertionError('The terminator did not reach the join')
set_result(result, index, value)

with self.Pool(1) as pool:
result_handler_join = pool._result_handler.join

def join_result_handler():
try:
self.assertFalse(mapped.ready())
finally:
joining.set()
result_handler_join()

with unittest.mock.patch.object(MapResult, '_set', publish_chunk):
mapped = pool.map_async(
time.sleep, [0, support.LONG_TIMEOUT], chunksize=1,
)
self.assertTrue(publishing.wait(support.SHORT_TIMEOUT))
with unittest.mock.patch.object(
pool._result_handler, 'join', join_result_handler
):
pool.terminate()

with self.assertRaisesRegex(RuntimeError, 'Pool has been terminated'):
mapped.get(0)

@warnings_helper.ignore_fork_in_thread_deprecation_warnings()
def test_terminate_during_map_submission(self):
with self.Pool(1) as pool:
def inputs():
pool.terminate()
yield 2

with self.assertRaisesRegex(ValueError, 'Pool not running'):
pool.map_async(sqr, inputs())


class _TestPoolCallbackErrors(BaseTestCase):
ALLOWED_TYPES = ('processes', )

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Wake callers waiting for pending asynchronous results when a
:class:`multiprocessing.pool.Pool` is terminated. Calling ``get()`` on
an abandoned result now raises :exc:`RuntimeError`.
Loading