diff --git a/Doc/library/multiprocessing.rst b/Doc/library/multiprocessing.rst index a7d26f9b4554d7..b0cd5923156069 100644 --- a/Doc/library/multiprocessing.rst +++ b/Doc/library/multiprocessing.rst @@ -2067,7 +2067,7 @@ Process Pools One can create a pool of processes which will carry out tasks submitted to it with the :class:`Pool` class. -.. class:: Pool([processes[, initializer[, initargs[, maxtasksperchild [, context]]]]]) +.. class:: Pool([processes[, initializer[, initargs[, expect_initret[, maxtasksperchild[, context]]]]]) A process pool object which controls a pool of worker processes to which jobs can be submitted. It supports asynchronous results with timeouts and @@ -2079,6 +2079,11 @@ with the :class:`Pool` class. If *initializer* is not ``None`` then each worker process will call ``initializer(*initargs)`` when it starts. + If *expect_initret* is ``True``, the return value of *initializer* will be + passed to each process' applied fuction as a kwarg named `initret`. This + can be used to pass data your Pool workers, as an alternative to declaring + globals. + *maxtasksperchild* is the number of tasks a worker process can complete before it will exit and be replaced with a fresh worker process, to enable unused resources to be freed. The default *maxtasksperchild* is ``None``, which @@ -2099,6 +2104,9 @@ with the :class:`Pool` class. .. versionadded:: 3.4 *context* + .. versionadded:: 3.8 + *expect_initret* + .. note:: Worker processes within a :class:`Pool` typically live for the complete diff --git a/Lib/multiprocessing/context.py b/Lib/multiprocessing/context.py index 871746b1a047b3..1dbb0af8f63579 100644 --- a/Lib/multiprocessing/context.py +++ b/Lib/multiprocessing/context.py @@ -111,12 +111,12 @@ def SimpleQueue(self): from .queues import SimpleQueue return SimpleQueue(ctx=self.get_context()) - def Pool(self, processes=None, initializer=None, initargs=(), - maxtasksperchild=None): + def Pool(self, processes=None, initializer=None, + initargs=(), expect_initret=False, maxtasksperchild=None): '''Returns a process pool object''' from .pool import Pool - return Pool(processes, initializer, initargs, maxtasksperchild, - context=self.get_context()) + return Pool(processes, initializer, initargs, expect_initret, + maxtasksperchild, context=self.get_context()) def RawValue(self, typecode_or_type, *args): '''Returns a shared object''' diff --git a/Lib/multiprocessing/dummy/__init__.py b/Lib/multiprocessing/dummy/__init__.py index 403f5e5198e4ed..9539093b8a16d9 100644 --- a/Lib/multiprocessing/dummy/__init__.py +++ b/Lib/multiprocessing/dummy/__init__.py @@ -119,8 +119,9 @@ def Manager(): def shutdown(): pass -def Pool(processes=None, initializer=None, initargs=()): +def Pool(processes=None, initializer=None, initargs=(), + expect_initret=False): from ..pool import ThreadPool - return ThreadPool(processes, initializer, initargs) + return ThreadPool(processes, initializer, initargs, expect_initret) JoinableQueue = Queue diff --git a/Lib/multiprocessing/pool.py b/Lib/multiprocessing/pool.py index 574b5db5afb684..ca8dbcf098d114 100644 --- a/Lib/multiprocessing/pool.py +++ b/Lib/multiprocessing/pool.py @@ -16,6 +16,7 @@ import threading import queue import itertools +import functools import collections import os import time @@ -40,11 +41,14 @@ job_counter = itertools.count() -def mapstar(args): - return list(map(*args)) +def mapstar(args, **kwargs): + return list( + map(functools.partial(args[0], **kwargs), + *args[1:])) -def starmapstar(args): - return list(itertools.starmap(args[0], args[1])) +def starmapstar(args, **kwargs): + return list( + itertools.starmap(functools.partial(args[0], **kwargs), args[1])) # # Hack to embed stringification of remote traceback in local traceback @@ -90,11 +94,13 @@ def __repr__(self): return "<%s: %s>" % (self.__class__.__name__, self) -def worker(inqueue, outqueue, initializer=None, initargs=(), maxtasks=None, - wrap_exception=False): +def worker(inqueue, outqueue, initializer=None, initargs=(), + expect_initret=False, maxtasks=None, wrap_exception=False): if (maxtasks is not None) and not (isinstance(maxtasks, int) and maxtasks >= 1): raise AssertionError("Maxtasks {!r} is not valid".format(maxtasks)) + + initret = None put = outqueue.put get = inqueue.get if hasattr(inqueue, '_writer'): @@ -102,7 +108,7 @@ def worker(inqueue, outqueue, initializer=None, initargs=(), maxtasks=None, outqueue._reader.close() if initializer is not None: - initializer(*initargs) + initret = initializer(*initargs) completed = 0 while maxtasks is None or (maxtasks and completed < maxtasks): @@ -118,7 +124,11 @@ def worker(inqueue, outqueue, initializer=None, initargs=(), maxtasks=None, job, i, func, args, kwds = task try: - result = (True, func(*args, **kwds)) + if expect_initret and func is not _helper_reraises_exception: + result = ( + True, func(*args, **kwds, initret=initret)) + else: + result = (True, func(*args, **kwds)) except Exception as e: if wrap_exception and func is not _helper_reraises_exception: e = ExceptionWithTraceback(e, e.__traceback__) @@ -154,7 +164,7 @@ def Process(ctx, *args, **kwds): return ctx.Process(*args, **kwds) def __init__(self, processes=None, initializer=None, initargs=(), - maxtasksperchild=None, context=None): + expect_initret=False, maxtasksperchild=None, context=None): self._ctx = context or get_context() self._setup_queues() self._taskqueue = queue.SimpleQueue() @@ -162,6 +172,7 @@ def __init__(self, processes=None, initializer=None, initargs=(), self._state = RUN self._maxtasksperchild = maxtasksperchild self._initializer = initializer + self._expect_initret = expect_initret self._initargs = initargs if processes is None: @@ -171,6 +182,9 @@ def __init__(self, processes=None, initializer=None, initargs=(), if initializer is not None and not callable(initializer): raise TypeError('initializer must be a callable') + if initializer is None and self._expect_initret: + raise ValueError( + "initializer can't be None if expect_initret is True") self._processes = processes self._pool = [] @@ -232,8 +246,10 @@ def _repopulate_pool(self): return self._repopulate_pool_static(self._ctx, self.Process, self._processes, self._pool, self._inqueue, - self._outqueue, self._initializer, + self._outqueue, + self._initializer, self._initargs, + self._expect_initret, self._maxtasksperchild, self._wrap_exception) @@ -244,11 +260,13 @@ def _repopulate_pool_static(ctx, Process, processes, pool, inqueue, """Bring the number of pool processes up to the specified number, for use after reaping workers which have exited. """ + for i in range(processes - len(pool)): w = Process(ctx, target=worker, args=(inqueue, outqueue, - initializer, - initargs, maxtasksperchild, + initializer, initargs, + expect_initret, + maxtasksperchild, wrap_exception) ) pool.append(w) @@ -264,7 +282,10 @@ def _maintain_pool(ctx, Process, processes, pool, inqueue, outqueue, """Clean up any exited workers and start replacements for them. """ if Pool._join_exited_workers(pool): - Pool._repopulate_pool_static(ctx, Process, processes, pool, + Pool. + + + (ctx, Process, processes, pool, inqueue, outqueue, initializer, initargs, maxtasksperchild, wrap_exception) @@ -824,8 +845,9 @@ def Process(ctx, *args, **kwds): from .dummy import Process return Process(*args, **kwds) - def __init__(self, processes=None, initializer=None, initargs=()): - Pool.__init__(self, processes, initializer, initargs) + def __init__(self, processes=None, initializer=None, + initargs=(), expect_initret=False): + Pool.__init__(self, processes, initializer, initargs, expect_initret) def _setup_queues(self): self._inqueue = queue.SimpleQueue() diff --git a/Lib/test/_test_multiprocessing.py b/Lib/test/_test_multiprocessing.py index 814aae8fa3754e..f8bef556389fb6 100644 --- a/Lib/test/_test_multiprocessing.py +++ b/Lib/test/_test_multiprocessing.py @@ -8,6 +8,7 @@ import time import io import itertools +import functools import sys import os import gc @@ -86,7 +87,7 @@ def join_process(process): # LOG_LEVEL = util.SUBWARNING -#LOG_LEVEL = logging.DEBUG +# LOG_LEVEL = logging.DEBUG DELTA = 0.1 CHECK_TIMINGS = False # making true makes tests take a lot longer @@ -2190,6 +2191,12 @@ def test_namespace(self): # # # +def add_to(x, initret=None, wait=0.0): + time.sleep(wait) + return x + initret + +def dist_3d(a, b, initret=None): + return (a**2 + b**2 + initret**2)**.5 def sqr(x, wait=0.0): time.sleep(wait) @@ -2205,6 +2212,14 @@ def raise_large_valuerror(wait): def identity(x): return x +def identity_wrapper(x, initret=None): + return x + +def sleep_wrapper(x, initret=None): + time.sleep(x) + +# Need above wrappers globally defined so we can pickle. + class CountedObject(object): n_instances = 0 @@ -2245,6 +2260,16 @@ def test_apply(self): self.assertEqual(papply(sqr, (5,)), sqr(5)) self.assertEqual(papply(sqr, (), {'x':3}), sqr(x=3)) + def test_apply_kwds_are_reset(self): + # `kwds` arg of `apply()` is either a (mutable) dict, or None + self.assertTrue(self.pool.apply.__defaults__ in [ + ((), {}), + None]) + self.pool.apply(sqr, (5,)) + self.assertTrue(self.pool.apply.__defaults__ in [ + ((), {}), + None]) + def test_map(self): pmap = self.pool.map self.assertEqual(pmap(sqr, list(range(10))), list(map(sqr, list(range(10))))) @@ -2556,6 +2581,249 @@ def test_del_pool(self): gc.collect() self.assertIsNone(wr()) +class _TestInitRetPool(BaseTestCase): + + _initret = 10 + + @classmethod + def _initializer(cls): + return cls._initret + + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.pool = cls.Pool( + 4, initializer=cls._initializer, expect_initret=True) + cls.curried_add_to = functools.partial( + add_to, initret=cls._initret) + cls.curried_dist_3d = functools.partial( + dist_3d, initret=cls._initret) + + @classmethod + def tearDownClass(cls): + cls.pool.terminate() + cls.pool.join() + cls.pool = None + super().tearDownClass() + + def test_apply_kwds_are_reset(self): + # `kwds` arg of `apply()` is either a (mutable) dict, or None + self.assertTrue(self.pool.apply.__defaults__ in [ + ((), {}), + None]) + self.pool.apply(add_to, (5,)) + self.assertTrue(self.pool.apply.__defaults__ in [ + ((), {}), + None]) + + def test_apply(self): + actual = self.pool.apply(add_to, (5,)) + expected = self.curried_add_to(5) + self.assertEqual(actual, expected) + + actual = self.pool.apply(add_to, (), {'x': 5}) + expected = self.curried_add_to(x=5) + self.assertEqual(actual, expected) + + def test_map(self): + pmap = self.pool.map + self.assertEqual(pmap(add_to, list(range(10))), + list(map(self.curried_add_to, + list(range(10))))) + self.assertEqual(pmap(add_to, list(range(100)), chunksize=20), + list(map(self.curried_add_to, + list(range(100))))) + def test_starmap(self): + psmap = self.pool.starmap + tuples = list(zip(range(10), range(9,-1, -1))) + self.assertEqual(psmap(dist_3d, tuples), + list(itertools.starmap(self.curried_dist_3d, tuples))) + tuples = list(zip(range(100), range(99,-1, -1))) + self.assertEqual(psmap(dist_3d, tuples, chunksize=20), + list(itertools.starmap(self.curried_dist_3d, tuples))) + + def test_starmap_async(self): + tuples = list(zip(range(100), range(99,-1, -1))) + self.assertEqual(self.pool.starmap_async(dist_3d, tuples).get(), + list(itertools.starmap(self.curried_dist_3d, tuples))) + def test_map_async(self): + self.assertEqual(self.pool.map_async(add_to, list(range(10))).get(), + list(map(self.curried_add_to, list(range(10))))) + + def test_map_unplicklable(self): + # Issue #19425 -- failure to pickle should not cause a hang + if self.TYPE == 'threads': + self.skipTest('test not appropriate for {}'.format(self.TYPE)) + class A(object): + def __reduce__(self): + raise RuntimeError('cannot pickle') + with self.assertRaises(RuntimeError): + self.pool.map(add_to, [A()]*10) + + def test_map_chunksize(self): + try: + self.pool.map_async(add_to, [], chunksize=1).get(timeout=TIMEOUT1) + except multiprocessing.TimeoutError: + self.fail("pool.map_async with chunksize stalled on null list") + + def test_map_handle_iterable_exception(self): + if self.TYPE == 'manager': + self.skipTest('test not appropriate for {}'.format(self.TYPE)) + + # SayWhenError seen at the very first of the iterable + with self.assertRaises(SayWhenError): + self.pool.map(add_to, exception_throwing_generator(1, -1), 1) + # again, make sure it's reentrant + with self.assertRaises(SayWhenError): + self.pool.map(add_to, exception_throwing_generator(1, -1), 1) + + with self.assertRaises(SayWhenError): + self.pool.map(add_to, exception_throwing_generator(10, 3), 1) + + class SpecialIterable: + def __iter__(self): + return self + def __next__(self): + raise SayWhenError + def __len__(self): + return 1 + with self.assertRaises(SayWhenError): + self.pool.map(add_to, SpecialIterable(), 1) + with self.assertRaises(SayWhenError): + self.pool.map(add_to, SpecialIterable(), 1) + + def test_async(self): + res = self.pool.apply_async(add_to, (7,), {'wait': TIMEOUT1}) + get = TimingWrapper(res.get) + self.assertEqual(get(), self.curried_add_to(7)) + self.assertTimingAlmostEqual(get.elapsed, TIMEOUT1) + + def test_async_timeout(self): + res = self.pool.apply_async(add_to, (6,), {'wait': TIMEOUT2 + 1.0}) + get = TimingWrapper(res.get) + self.assertRaises(multiprocessing.TimeoutError, get, timeout=TIMEOUT2) + self.assertTimingAlmostEqual(get.elapsed, TIMEOUT2) + + def test_imap(self): + it = self.pool.imap(add_to, list(range(10))) + self.assertEqual(list(it), list(map(self.curried_add_to, + list(range(10))))) + + it = self.pool.imap(add_to, list(range(10))) + for i in range(10): + self.assertEqual(next(it), self.curried_add_to(i)) + self.assertRaises(StopIteration, it.__next__) + + it = self.pool.imap(add_to, list(range(1000)), chunksize=100) + for i in range(1000): + self.assertEqual(next(it), self.curried_add_to(i)) + self.assertRaises(StopIteration, it.__next__) + + def test_imap_handle_iterable_exception(self): + if self.TYPE == 'manager': + self.skipTest('test not appropriate for {}'.format(self.TYPE)) + + # SayWhenError seen at the very first of the iterable + it = self.pool.imap(add_to, exception_throwing_generator(1, -1), 1) + self.assertRaises(SayWhenError, it.__next__) + # again, make sure it's reentrant + it = self.pool.imap(add_to, exception_throwing_generator(1, -1), 1) + self.assertRaises(SayWhenError, it.__next__) + + it = self.pool.imap(add_to, exception_throwing_generator(10, 3), 1) + for i in range(3): + self.assertEqual(next(it), self.curried_add_to(i)) + self.assertRaises(SayWhenError, it.__next__) + + # SayWhenError seen at start of problematic chunk's results + it = self.pool.imap(add_to, exception_throwing_generator(20, 7), 2) + for i in range(6): + self.assertEqual(next(it), self.curried_add_to(i)) + self.assertRaises(SayWhenError, it.__next__) + it = self.pool.imap(add_to, exception_throwing_generator(20, 7), 4) + for i in range(4): + self.assertEqual(next(it), self.curried_add_to(i)) + self.assertRaises(SayWhenError, it.__next__) + + def test_imap_unordered(self): + it = self.pool.imap_unordered(add_to, list(range(10))) + self.assertEqual(sorted(it), list(map(self.curried_add_to, + list(range(10))))) + + it = self.pool.imap_unordered(add_to, list(range(1000)), chunksize=100) + self.assertEqual(sorted(it), list(map(self.curried_add_to, + list(range(1000))))) + + def test_imap_unordered_handle_iterable_exception(self): + if self.TYPE == 'manager': + self.skipTest('test not appropriate for {}'.format(self.TYPE)) + + # SayWhenError seen at the very first of the iterable + it = self.pool.imap_unordered(add_to, + exception_throwing_generator(1, -1), + 1) + self.assertRaises(SayWhenError, it.__next__) + # again, make sure it's reentrant + it = self.pool.imap_unordered(add_to, + exception_throwing_generator(1, -1), + 1) + self.assertRaises(SayWhenError, it.__next__) + + it = self.pool.imap_unordered(add_to, + exception_throwing_generator(10, 3), + 1) + expected_values = list(map(self.curried_add_to, list(range(10)))) + with self.assertRaises(SayWhenError): + # imap_unordered makes it difficult to anticipate the SayWhenError + for i in range(10): + value = next(it) + self.assertIn(value, expected_values) + expected_values.remove(value) + + it = self.pool.imap_unordered(add_to, + exception_throwing_generator(20, 7), + 2) + expected_values = list(map(self.curried_add_to, list(range(20)))) + with self.assertRaises(SayWhenError): + for i in range(20): + value = next(it) + self.assertIn(value, expected_values) + expected_values.remove(value) + + def test_terminate(self): + result = self.pool.map_async( + sleep_wrapper, [0.1 for i in range(10000)], chunksize=1 + ) + self.pool.terminate() + join = TimingWrapper(self.pool.join) + join() + # Sanity check the pool didn't wait for all tasks to finish + self.assertLess(join.elapsed, 2.0) + + def test_context(self): + if self.TYPE == 'processes': + L = list(range(10)) + expected = [self.curried_add_to(i) for i in L] + with self.Pool(2, initializer=self._initializer, + expect_initret=True) as p: + r = p.map_async(add_to, L) + self.assertEqual(r.get(), expected) + self.assertRaises(ValueError, p.map_async, add_to, L) + + def test_release_task_refs(self): + # Issue #29861: task arguments and results should not be kept + # alive after we are done with them. + objs = [CountedObject() for i in range(10)] + refs = [weakref.ref(o) for o in objs] + self.pool.map(identity_wrapper, objs) + + del objs + time.sleep(DELTA) # let threaded cleanup code run + self.assertEqual(set(wr() for wr in refs), {None}) + # With a process pool, copies of the objects are returned, check + # they were released too. + self.assertEqual(CountedObject.n_instances, 0) + def raising(): raise KeyError("key")