From 79e4fa256e7b92a31ba03f9838c213c6eb71df1e Mon Sep 17 00:00:00 2001 From: Sean Harrington Date: Mon, 20 Aug 2018 15:41:02 -0400 Subject: [PATCH 1/4] Pool(...expect_initret=False...) kwarg to allow more flexible initialization of worker processes --- Lib/multiprocessing/context.py | 8 ++++---- Lib/multiprocessing/pool.py | 28 ++++++++++++++++++++-------- 2 files changed, 24 insertions(+), 12 deletions(-) diff --git a/Lib/multiprocessing/context.py b/Lib/multiprocessing/context.py index 871746b1a047b3..0131a7497f90f1 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, expect_initret=False, + initargs=(), 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, expect_initret, + initargs, maxtasksperchild, context=self.get_context()) def RawValue(self, typecode_or_type, *args): '''Returns a shared object''' diff --git a/Lib/multiprocessing/pool.py b/Lib/multiprocessing/pool.py index 3e9a0d6b48679f..5cffea049de34a 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,8 +41,10 @@ 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])) @@ -90,11 +93,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 +107,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): @@ -117,6 +122,8 @@ def worker(inqueue, outqueue, initializer=None, initargs=(), maxtasks=None, break job, i, func, args, kwds = task + if expect_initret: + kwds['initret'] = initret try: result = (True, func(*args, **kwds)) except Exception as e: @@ -153,7 +160,7 @@ def Process(self, *args, **kwds): return self._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() @@ -161,6 +168,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: @@ -170,6 +178,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 = [] @@ -231,8 +242,9 @@ def _repopulate_pool(self): for i in range(self._processes - len(self._pool)): w = self.Process(target=worker, args=(self._inqueue, self._outqueue, - self._initializer, - self._initargs, self._maxtasksperchild, + self._initializer, self._initargs, + self._expect_initret, + self._maxtasksperchild, self._wrap_exception) ) self._pool.append(w) From 38510c8231bac9f0213f0e43aed59aff8546d850 Mon Sep 17 00:00:00 2001 From: Sean Harrington Date: Fri, 14 Sep 2018 06:47:54 -0400 Subject: [PATCH 2/4] Post-fork initialization of multiprocessing.Pool workers via expect_initret kwarg --- Lib/multiprocessing/context.py | 8 +- Lib/multiprocessing/dummy/__init__.py | 5 +- Lib/multiprocessing/pool.py | 18 +- Lib/test/_test_multiprocessing.py | 270 +++++++++++++++++++++++++- 4 files changed, 287 insertions(+), 14 deletions(-) diff --git a/Lib/multiprocessing/context.py b/Lib/multiprocessing/context.py index 0131a7497f90f1..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, expect_initret=False, - 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, expect_initret, - 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 5cffea049de34a..383ac5dc08913c 100644 --- a/Lib/multiprocessing/pool.py +++ b/Lib/multiprocessing/pool.py @@ -46,8 +46,9 @@ def mapstar(args, **kwargs): 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 @@ -122,10 +123,12 @@ def worker(inqueue, outqueue, initializer=None, initargs=(), break job, i, func, args, kwds = task - if expect_initret: - kwds['initret'] = initret 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__) @@ -810,8 +813,9 @@ def Process(*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 749cf8c4fd2c49..9286e5167c6e22 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 @@ -88,7 +89,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 @@ -2169,6 +2170,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) @@ -2184,6 +2191,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 @@ -2224,6 +2239,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))))) @@ -2529,6 +2554,249 @@ def test_release_task_refs(self): self.assertEqual(CountedObject.n_instances, 0) +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") From 583181ccb4e345f826b2dc384e560237e4fe6a82 Mon Sep 17 00:00:00 2001 From: Sean Harrington Date: Thu, 11 Oct 2018 19:13:49 -0400 Subject: [PATCH 3/4] bpo-34837 Doc Blurb --- Doc/library/multiprocessing.rst | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/Doc/library/multiprocessing.rst b/Doc/library/multiprocessing.rst index 504f3a1c3c33bf..fe6e7a728316f7 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 From 0091cc65367d6199f57aaaaf753d70c8e1c92337 Mon Sep 17 00:00:00 2001 From: Sean Harrington Date: Thu, 11 Oct 2018 19:21:55 -0400 Subject: [PATCH 4/4] Typo passing self._expect_initret to static method --- Lib/multiprocessing/pool.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Lib/multiprocessing/pool.py b/Lib/multiprocessing/pool.py index 5bcaf0d1e52e2d..ca8dbcf098d114 100644 --- a/Lib/multiprocessing/pool.py +++ b/Lib/multiprocessing/pool.py @@ -249,7 +249,7 @@ def _repopulate_pool(self): self._outqueue, self._initializer, self._initargs, - self._exp + self._expect_initret, self._maxtasksperchild, self._wrap_exception)