2
# Module providing the `Pool` class for managing a process pool
4
# multiprocessing/pool.py
6
# Copyright (c) 2006-2008, R Oudkerk
9
# Redistribution and use in source and binary forms, with or without
10
# modification, are permitted provided that the following conditions
13
# 1. Redistributions of source code must retain the above copyright
14
# notice, this list of conditions and the following disclaimer.
15
# 2. Redistributions in binary form must reproduce the above copyright
16
# notice, this list of conditions and the following disclaimer in the
17
# documentation and/or other materials provided with the distribution.
18
# 3. Neither the name of author nor the names of any contributors may be
19
# used to endorse or promote products derived from this software
20
# without specific prior written permission.
22
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND
23
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25
# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
26
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47
from multiprocessing import Process, cpu_count, TimeoutError
48
from multiprocessing.util import Finalize, debug
51
# Constants representing the state of a pool
62
job_counter = itertools.count()
68
# Code run by worker processes
71
class MaybeEncodingError(Exception):
72
"""Wraps possible unpickleable errors, so they can be
73
safely sent through the socket."""
75
def __init__(self, exc, value):
77
self.value = repr(value)
78
super(MaybeEncodingError, self).__init__(self.exc, self.value)
81
return "Error sending result: '%s'. Reason: '%s'" % (self.value,
85
return "<MaybeEncodingError: %s>" % str(self)
88
def worker(inqueue, outqueue, initializer=None, initargs=(), maxtasks=None):
89
assert maxtasks is None or (type(maxtasks) == int and maxtasks > 0)
92
if hasattr(inqueue, '_writer'):
93
inqueue._writer.close()
94
outqueue._reader.close()
96
if initializer is not None:
97
initializer(*initargs)
100
while maxtasks is None or (maxtasks and completed < maxtasks):
103
except (EOFError, IOError):
104
debug('worker got EOFError or IOError -- exiting')
108
debug('worker got sentinel -- exiting')
111
job, i, func, args, kwds = task
113
result = (True, func(*args, **kwds))
117
put((job, i, result))
118
except Exception as e:
119
wrapped = MaybeEncodingError(e, result[1])
120
debug("Possible encoding error while sending result: %s" % (
122
put((job, i, (False, wrapped)))
124
debug('worker exiting after %d tasks' % completed)
127
# Class representing a process pool
132
Class which supports an async version of the `apply()` builtin
136
def __init__(self, processes=None, initializer=None, initargs=(),
137
maxtasksperchild=None):
139
self._taskqueue = Queue.Queue()
142
self._maxtasksperchild = maxtasksperchild
143
self._initializer = initializer
144
self._initargs = initargs
146
if processes is None:
148
processes = cpu_count()
149
except NotImplementedError:
152
raise ValueError("Number of processes must be at least 1")
154
if initializer is not None and not hasattr(initializer, '__call__'):
155
raise TypeError('initializer must be a callable')
157
self._processes = processes
159
self._repopulate_pool()
161
self._worker_handler = threading.Thread(
162
target=Pool._handle_workers,
165
self._worker_handler.daemon = True
166
self._worker_handler._state = RUN
167
self._worker_handler.start()
170
self._task_handler = threading.Thread(
171
target=Pool._handle_tasks,
172
args=(self._taskqueue, self._quick_put, self._outqueue,
173
self._pool, self._cache)
175
self._task_handler.daemon = True
176
self._task_handler._state = RUN
177
self._task_handler.start()
179
self._result_handler = threading.Thread(
180
target=Pool._handle_results,
181
args=(self._outqueue, self._quick_get, self._cache)
183
self._result_handler.daemon = True
184
self._result_handler._state = RUN
185
self._result_handler.start()
187
self._terminate = Finalize(
188
self, self._terminate_pool,
189
args=(self._taskqueue, self._inqueue, self._outqueue, self._pool,
190
self._worker_handler, self._task_handler,
191
self._result_handler, self._cache),
195
def _join_exited_workers(self):
196
"""Cleanup after any worker processes which have exited due to reaching
197
their specified lifetime. Returns True if any workers were cleaned up.
200
for i in reversed(range(len(self._pool))):
201
worker = self._pool[i]
202
if worker.exitcode is not None:
204
debug('cleaning up worker %d' % i)
210
def _repopulate_pool(self):
211
"""Bring the number of pool processes up to the specified number,
212
for use after reaping workers which have exited.
214
for i in range(self._processes - len(self._pool)):
215
w = self.Process(target=worker,
216
args=(self._inqueue, self._outqueue,
218
self._initargs, self._maxtasksperchild)
221
w.name = w.name.replace('Process', 'PoolWorker')
224
debug('added worker')
226
def _maintain_pool(self):
227
"""Clean up any exited workers and start replacements for them.
229
if self._join_exited_workers():
230
self._repopulate_pool()
232
def _setup_queues(self):
233
from .queues import SimpleQueue
234
self._inqueue = SimpleQueue()
235
self._outqueue = SimpleQueue()
236
self._quick_put = self._inqueue._writer.send
237
self._quick_get = self._outqueue._reader.recv
239
def apply(self, func, args=(), kwds={}):
241
Equivalent of `apply()` builtin
243
assert self._state == RUN
244
return self.apply_async(func, args, kwds).get()
246
def map(self, func, iterable, chunksize=None):
248
Equivalent of `map()` builtin
250
assert self._state == RUN
251
return self.map_async(func, iterable, chunksize).get()
253
def imap(self, func, iterable, chunksize=1):
255
Equivalent of `itertools.imap()` -- can be MUCH slower than `Pool.map()`
257
assert self._state == RUN
259
result = IMapIterator(self._cache)
260
self._taskqueue.put((((result._job, i, func, (x,), {})
261
for i, x in enumerate(iterable)), result._set_length))
265
task_batches = Pool._get_tasks(func, iterable, chunksize)
266
result = IMapIterator(self._cache)
267
self._taskqueue.put((((result._job, i, mapstar, (x,), {})
268
for i, x in enumerate(task_batches)), result._set_length))
269
return (item for chunk in result for item in chunk)
271
def imap_unordered(self, func, iterable, chunksize=1):
273
Like `imap()` method but ordering of results is arbitrary
275
assert self._state == RUN
277
result = IMapUnorderedIterator(self._cache)
278
self._taskqueue.put((((result._job, i, func, (x,), {})
279
for i, x in enumerate(iterable)), result._set_length))
283
task_batches = Pool._get_tasks(func, iterable, chunksize)
284
result = IMapUnorderedIterator(self._cache)
285
self._taskqueue.put((((result._job, i, mapstar, (x,), {})
286
for i, x in enumerate(task_batches)), result._set_length))
287
return (item for chunk in result for item in chunk)
289
def apply_async(self, func, args=(), kwds={}, callback=None):
291
Asynchronous equivalent of `apply()` builtin
293
assert self._state == RUN
294
result = ApplyResult(self._cache, callback)
295
self._taskqueue.put(([(result._job, None, func, args, kwds)], None))
298
def map_async(self, func, iterable, chunksize=None, callback=None):
300
Asynchronous equivalent of `map()` builtin
302
assert self._state == RUN
303
if not hasattr(iterable, '__len__'):
304
iterable = list(iterable)
306
if chunksize is None:
307
chunksize, extra = divmod(len(iterable), len(self._pool) * 4)
310
if len(iterable) == 0:
313
task_batches = Pool._get_tasks(func, iterable, chunksize)
314
result = MapResult(self._cache, chunksize, len(iterable), callback)
315
self._taskqueue.put((((result._job, i, mapstar, (x,), {})
316
for i, x in enumerate(task_batches)), None))
320
def _handle_workers(pool):
321
thread = threading.current_thread()
323
# Keep maintaining workers until the cache gets drained, unless the pool
325
while thread._state == RUN or (pool._cache and thread._state != TERMINATE):
326
pool._maintain_pool()
328
# send sentinel to stop workers
329
pool._taskqueue.put(None)
330
debug('worker handler exiting')
333
def _handle_tasks(taskqueue, put, outqueue, pool, cache):
334
thread = threading.current_thread()
336
for taskseq, set_length in iter(taskqueue.get, None):
340
for i, task in enumerate(taskseq):
342
debug('task handler found thread._state != RUN')
346
except Exception as e:
349
cache[job]._set(ind, (False, e))
354
debug('doing set_length()')
358
except Exception as ex:
359
job, ind = task[:2] if task else (0, 0)
361
cache[job]._set(ind + 1, (False, ex))
363
debug('doing set_length()')
366
debug('task handler got sentinel')
370
# tell result handler to finish when cache is empty
371
debug('task handler sending sentinel to result handler')
374
# tell workers there is no more work
375
debug('task handler sending sentinel to workers')
379
debug('task handler got IOError when sending sentinels')
381
debug('task handler exiting')
384
def _handle_results(outqueue, get, cache):
385
thread = threading.current_thread()
390
except (IOError, EOFError):
391
debug('result handler got EOFError/IOError -- exiting')
395
assert thread._state == TERMINATE
396
debug('result handler found thread._state=TERMINATE')
400
debug('result handler got sentinel')
405
cache[job]._set(i, obj)
409
while cache and thread._state != TERMINATE:
412
except (IOError, EOFError):
413
debug('result handler got EOFError/IOError -- exiting')
417
debug('result handler ignoring extra sentinel')
421
cache[job]._set(i, obj)
425
if hasattr(outqueue, '_reader'):
426
debug('ensuring that outqueue is not full')
427
# If we don't make room available in outqueue then
428
# attempts to add the sentinel (None) to outqueue may
429
# block. There is guaranteed to be no more than 2 sentinels.
432
if not outqueue._reader.poll():
435
except (IOError, EOFError):
438
debug('result handler exiting: len(cache)=%s, thread._state=%s',
439
len(cache), thread._state)
442
def _get_tasks(func, it, size):
445
x = tuple(itertools.islice(it, size))
450
def __reduce__(self):
451
raise NotImplementedError(
452
'pool objects cannot be passed between processes or pickled'
456
debug('closing pool')
457
if self._state == RUN:
459
self._worker_handler._state = CLOSE
462
debug('terminating pool')
463
self._state = TERMINATE
464
self._worker_handler._state = TERMINATE
468
debug('joining pool')
469
assert self._state in (CLOSE, TERMINATE)
470
self._worker_handler.join()
471
self._task_handler.join()
472
self._result_handler.join()
477
def _help_stuff_finish(inqueue, task_handler, size):
478
# task_handler may be blocked trying to put items on inqueue
479
debug('removing tasks from inqueue until task handler finished')
480
inqueue._rlock.acquire()
481
while task_handler.is_alive() and inqueue._reader.poll():
482
inqueue._reader.recv()
486
def _terminate_pool(cls, taskqueue, inqueue, outqueue, pool,
487
worker_handler, task_handler, result_handler, cache):
488
# this is guaranteed to only be called once
489
debug('finalizing pool')
491
worker_handler._state = TERMINATE
492
task_handler._state = TERMINATE
494
debug('helping task handler/workers to finish')
495
cls._help_stuff_finish(inqueue, task_handler, len(pool))
497
assert result_handler.is_alive() or len(cache) == 0
499
result_handler._state = TERMINATE
500
outqueue.put(None) # sentinel
502
# We must wait for the worker handler to exit before terminating
503
# workers because we don't want workers to be restarted behind our back.
504
debug('joining worker handler')
505
if threading.current_thread() is not worker_handler:
506
worker_handler.join(1e100)
508
# Terminate workers which haven't already finished.
509
if pool and hasattr(pool[0], 'terminate'):
510
debug('terminating workers')
512
if p.exitcode is None:
515
debug('joining task handler')
516
if threading.current_thread() is not task_handler:
517
task_handler.join(1e100)
519
debug('joining result handler')
520
if threading.current_thread() is not result_handler:
521
result_handler.join(1e100)
523
if pool and hasattr(pool[0], 'terminate'):
524
debug('joining pool workers')
527
# worker has not yet exited
528
debug('cleaning up worker %d' % p.pid)
532
# Class whose instances are returned by `Pool.apply_async()`
535
class ApplyResult(object):
537
def __init__(self, cache, callback):
538
self._cond = threading.Condition(threading.Lock())
539
self._job = job_counter.next()
542
self._callback = callback
543
cache[self._job] = self
548
def successful(self):
552
def wait(self, timeout=None):
556
self._cond.wait(timeout)
560
def get(self, timeout=None):
569
def _set(self, i, obj):
570
self._success, self._value = obj
571
if self._callback and self._success:
572
self._callback(self._value)
579
del self._cache[self._job]
581
AsyncResult = ApplyResult # create alias -- see #17805
584
# Class whose instances are returned by `Pool.map_async()`
587
class MapResult(ApplyResult):
589
def __init__(self, cache, chunksize, length, callback):
590
ApplyResult.__init__(self, cache, callback)
592
self._value = [None] * length
593
self._chunksize = chunksize
595
self._number_left = 0
599
self._number_left = length//chunksize + bool(length % chunksize)
601
def _set(self, i, success_result):
602
success, result = success_result
604
self._value[i*self._chunksize:(i+1)*self._chunksize] = result
605
self._number_left -= 1
606
if self._number_left == 0:
608
self._callback(self._value)
609
del self._cache[self._job]
618
self._success = False
620
del self._cache[self._job]
629
# Class whose instances are returned by `Pool.imap()`
632
class IMapIterator(object):
634
def __init__(self, cache):
635
self._cond = threading.Condition(threading.Lock())
636
self._job = job_counter.next()
638
self._items = collections.deque()
642
cache[self._job] = self
647
def next(self, timeout=None):
651
item = self._items.popleft()
653
if self._index == self._length:
655
self._cond.wait(timeout)
657
item = self._items.popleft()
659
if self._index == self._length:
665
success, value = item
670
__next__ = next # XXX
672
def _set(self, i, obj):
676
self._items.append(obj)
678
while self._index in self._unsorted:
679
obj = self._unsorted.pop(self._index)
680
self._items.append(obj)
684
self._unsorted[i] = obj
686
if self._index == self._length:
687
del self._cache[self._job]
691
def _set_length(self, length):
694
self._length = length
695
if self._index == self._length:
697
del self._cache[self._job]
702
# Class whose instances are returned by `Pool.imap_unordered()`
705
class IMapUnorderedIterator(IMapIterator):
707
def _set(self, i, obj):
710
self._items.append(obj)
713
if self._index == self._length:
714
del self._cache[self._job]
722
class ThreadPool(Pool):
724
from .dummy import Process
726
def __init__(self, processes=None, initializer=None, initargs=()):
727
Pool.__init__(self, processes, initializer, initargs)
729
def _setup_queues(self):
730
self._inqueue = Queue.Queue()
731
self._outqueue = Queue.Queue()
732
self._quick_put = self._inqueue.put
733
self._quick_get = self._outqueue.get
736
def _help_stuff_finish(inqueue, task_handler, size):
737
# put sentinels at head of inqueue to make workers finish
738
inqueue.not_empty.acquire()
740
inqueue.queue.clear()
741
inqueue.queue.extend([None] * size)
742
inqueue.not_empty.notify_all()
744
inqueue.not_empty.release()
2
# Module providing the `Pool` class for managing a process pool
4
# multiprocessing/pool.py
6
# Copyright (c) 2006-2008, R Oudkerk
9
# Redistribution and use in source and binary forms, with or without
10
# modification, are permitted provided that the following conditions
13
# 1. Redistributions of source code must retain the above copyright
14
# notice, this list of conditions and the following disclaimer.
15
# 2. Redistributions in binary form must reproduce the above copyright
16
# notice, this list of conditions and the following disclaimer in the
17
# documentation and/or other materials provided with the distribution.
18
# 3. Neither the name of author nor the names of any contributors may be
19
# used to endorse or promote products derived from this software
20
# without specific prior written permission.
22
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND
23
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25
# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
26
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47
from multiprocessing import Process, cpu_count, TimeoutError
48
from multiprocessing.util import Finalize, debug
51
# Constants representing the state of a pool
62
job_counter = itertools.count()
68
# Code run by worker processes
71
class MaybeEncodingError(Exception):
72
"""Wraps possible unpickleable errors, so they can be
73
safely sent through the socket."""
75
def __init__(self, exc, value):
77
self.value = repr(value)
78
super(MaybeEncodingError, self).__init__(self.exc, self.value)
81
return "Error sending result: '%s'. Reason: '%s'" % (self.value,
85
return "<MaybeEncodingError: %s>" % str(self)
88
def worker(inqueue, outqueue, initializer=None, initargs=(), maxtasks=None):
89
assert maxtasks is None or (type(maxtasks) == int and maxtasks > 0)
92
if hasattr(inqueue, '_writer'):
93
inqueue._writer.close()
94
outqueue._reader.close()
96
if initializer is not None:
97
initializer(*initargs)
100
while maxtasks is None or (maxtasks and completed < maxtasks):
103
except (EOFError, IOError):
104
debug('worker got EOFError or IOError -- exiting')
108
debug('worker got sentinel -- exiting')
111
job, i, func, args, kwds = task
113
result = (True, func(*args, **kwds))
117
put((job, i, result))
118
except Exception as e:
119
wrapped = MaybeEncodingError(e, result[1])
120
debug("Possible encoding error while sending result: %s" % (
122
put((job, i, (False, wrapped)))
124
debug('worker exiting after %d tasks' % completed)
127
# Class representing a process pool
132
Class which supports an async version of the `apply()` builtin
136
def __init__(self, processes=None, initializer=None, initargs=(),
137
maxtasksperchild=None):
139
self._taskqueue = Queue.Queue()
142
self._maxtasksperchild = maxtasksperchild
143
self._initializer = initializer
144
self._initargs = initargs
146
if processes is None:
148
processes = cpu_count()
149
except NotImplementedError:
152
raise ValueError("Number of processes must be at least 1")
154
if initializer is not None and not hasattr(initializer, '__call__'):
155
raise TypeError('initializer must be a callable')
157
self._processes = processes
159
self._repopulate_pool()
161
self._worker_handler = threading.Thread(
162
target=Pool._handle_workers,
165
self._worker_handler.daemon = True
166
self._worker_handler._state = RUN
167
self._worker_handler.start()
170
self._task_handler = threading.Thread(
171
target=Pool._handle_tasks,
172
args=(self._taskqueue, self._quick_put, self._outqueue,
173
self._pool, self._cache)
175
self._task_handler.daemon = True
176
self._task_handler._state = RUN
177
self._task_handler.start()
179
self._result_handler = threading.Thread(
180
target=Pool._handle_results,
181
args=(self._outqueue, self._quick_get, self._cache)
183
self._result_handler.daemon = True
184
self._result_handler._state = RUN
185
self._result_handler.start()
187
self._terminate = Finalize(
188
self, self._terminate_pool,
189
args=(self._taskqueue, self._inqueue, self._outqueue, self._pool,
190
self._worker_handler, self._task_handler,
191
self._result_handler, self._cache),
195
def _join_exited_workers(self):
196
"""Cleanup after any worker processes which have exited due to reaching
197
their specified lifetime. Returns True if any workers were cleaned up.
200
for i in reversed(range(len(self._pool))):
201
worker = self._pool[i]
202
if worker.exitcode is not None:
204
debug('cleaning up worker %d' % i)
210
def _repopulate_pool(self):
211
"""Bring the number of pool processes up to the specified number,
212
for use after reaping workers which have exited.
214
for i in range(self._processes - len(self._pool)):
215
w = self.Process(target=worker,
216
args=(self._inqueue, self._outqueue,
218
self._initargs, self._maxtasksperchild)
221
w.name = w.name.replace('Process', 'PoolWorker')
224
debug('added worker')
226
def _maintain_pool(self):
227
"""Clean up any exited workers and start replacements for them.
229
if self._join_exited_workers():
230
self._repopulate_pool()
232
def _setup_queues(self):
233
from .queues import SimpleQueue
234
self._inqueue = SimpleQueue()
235
self._outqueue = SimpleQueue()
236
self._quick_put = self._inqueue._writer.send
237
self._quick_get = self._outqueue._reader.recv
239
def apply(self, func, args=(), kwds={}):
241
Equivalent of `apply()` builtin
243
assert self._state == RUN
244
return self.apply_async(func, args, kwds).get()
246
def map(self, func, iterable, chunksize=None):
248
Equivalent of `map()` builtin
250
assert self._state == RUN
251
return self.map_async(func, iterable, chunksize).get()
253
def imap(self, func, iterable, chunksize=1):
255
Equivalent of `itertools.imap()` -- can be MUCH slower than `Pool.map()`
257
assert self._state == RUN
259
result = IMapIterator(self._cache)
260
self._taskqueue.put((((result._job, i, func, (x,), {})
261
for i, x in enumerate(iterable)), result._set_length))
265
task_batches = Pool._get_tasks(func, iterable, chunksize)
266
result = IMapIterator(self._cache)
267
self._taskqueue.put((((result._job, i, mapstar, (x,), {})
268
for i, x in enumerate(task_batches)), result._set_length))
269
return (item for chunk in result for item in chunk)
271
def imap_unordered(self, func, iterable, chunksize=1):
273
Like `imap()` method but ordering of results is arbitrary
275
assert self._state == RUN
277
result = IMapUnorderedIterator(self._cache)
278
self._taskqueue.put((((result._job, i, func, (x,), {})
279
for i, x in enumerate(iterable)), result._set_length))
283
task_batches = Pool._get_tasks(func, iterable, chunksize)
284
result = IMapUnorderedIterator(self._cache)
285
self._taskqueue.put((((result._job, i, mapstar, (x,), {})
286
for i, x in enumerate(task_batches)), result._set_length))
287
return (item for chunk in result for item in chunk)
289
def apply_async(self, func, args=(), kwds={}, callback=None):
291
Asynchronous equivalent of `apply()` builtin
293
assert self._state == RUN
294
result = ApplyResult(self._cache, callback)
295
self._taskqueue.put(([(result._job, None, func, args, kwds)], None))
298
def map_async(self, func, iterable, chunksize=None, callback=None):
300
Asynchronous equivalent of `map()` builtin
302
assert self._state == RUN
303
if not hasattr(iterable, '__len__'):
304
iterable = list(iterable)
306
if chunksize is None:
307
chunksize, extra = divmod(len(iterable), len(self._pool) * 4)
310
if len(iterable) == 0:
313
task_batches = Pool._get_tasks(func, iterable, chunksize)
314
result = MapResult(self._cache, chunksize, len(iterable), callback)
315
self._taskqueue.put((((result._job, i, mapstar, (x,), {})
316
for i, x in enumerate(task_batches)), None))
320
def _handle_workers(pool):
321
thread = threading.current_thread()
323
# Keep maintaining workers until the cache gets drained, unless the pool
325
while thread._state == RUN or (pool._cache and thread._state != TERMINATE):
326
pool._maintain_pool()
328
# send sentinel to stop workers
329
pool._taskqueue.put(None)
330
debug('worker handler exiting')
333
def _handle_tasks(taskqueue, put, outqueue, pool, cache):
334
thread = threading.current_thread()
336
for taskseq, set_length in iter(taskqueue.get, None):
340
for i, task in enumerate(taskseq):
342
debug('task handler found thread._state != RUN')
346
except Exception as e:
349
cache[job]._set(ind, (False, e))
354
debug('doing set_length()')
358
except Exception as ex:
359
job, ind = task[:2] if task else (0, 0)
361
cache[job]._set(ind + 1, (False, ex))
363
debug('doing set_length()')
366
debug('task handler got sentinel')
370
# tell result handler to finish when cache is empty
371
debug('task handler sending sentinel to result handler')
374
# tell workers there is no more work
375
debug('task handler sending sentinel to workers')
379
debug('task handler got IOError when sending sentinels')
381
debug('task handler exiting')
384
def _handle_results(outqueue, get, cache):
385
thread = threading.current_thread()
390
except (IOError, EOFError):
391
debug('result handler got EOFError/IOError -- exiting')
395
assert thread._state == TERMINATE
396
debug('result handler found thread._state=TERMINATE')
400
debug('result handler got sentinel')
405
cache[job]._set(i, obj)
409
while cache and thread._state != TERMINATE:
412
except (IOError, EOFError):
413
debug('result handler got EOFError/IOError -- exiting')
417
debug('result handler ignoring extra sentinel')
421
cache[job]._set(i, obj)
425
if hasattr(outqueue, '_reader'):
426
debug('ensuring that outqueue is not full')
427
# If we don't make room available in outqueue then
428
# attempts to add the sentinel (None) to outqueue may
429
# block. There is guaranteed to be no more than 2 sentinels.
432
if not outqueue._reader.poll():
435
except (IOError, EOFError):
438
debug('result handler exiting: len(cache)=%s, thread._state=%s',
439
len(cache), thread._state)
442
def _get_tasks(func, it, size):
445
x = tuple(itertools.islice(it, size))
450
def __reduce__(self):
451
raise NotImplementedError(
452
'pool objects cannot be passed between processes or pickled'
456
debug('closing pool')
457
if self._state == RUN:
459
self._worker_handler._state = CLOSE
462
debug('terminating pool')
463
self._state = TERMINATE
464
self._worker_handler._state = TERMINATE
468
debug('joining pool')
469
assert self._state in (CLOSE, TERMINATE)
470
self._worker_handler.join()
471
self._task_handler.join()
472
self._result_handler.join()
477
def _help_stuff_finish(inqueue, task_handler, size):
478
# task_handler may be blocked trying to put items on inqueue
479
debug('removing tasks from inqueue until task handler finished')
480
inqueue._rlock.acquire()
481
while task_handler.is_alive() and inqueue._reader.poll():
482
inqueue._reader.recv()
486
def _terminate_pool(cls, taskqueue, inqueue, outqueue, pool,
487
worker_handler, task_handler, result_handler, cache):
488
# this is guaranteed to only be called once
489
debug('finalizing pool')
491
worker_handler._state = TERMINATE
492
task_handler._state = TERMINATE
494
debug('helping task handler/workers to finish')
495
cls._help_stuff_finish(inqueue, task_handler, len(pool))
497
assert result_handler.is_alive() or len(cache) == 0
499
result_handler._state = TERMINATE
500
outqueue.put(None) # sentinel
502
# We must wait for the worker handler to exit before terminating
503
# workers because we don't want workers to be restarted behind our back.
504
debug('joining worker handler')
505
if threading.current_thread() is not worker_handler:
506
worker_handler.join(1e100)
508
# Terminate workers which haven't already finished.
509
if pool and hasattr(pool[0], 'terminate'):
510
debug('terminating workers')
512
if p.exitcode is None:
515
debug('joining task handler')
516
if threading.current_thread() is not task_handler:
517
task_handler.join(1e100)
519
debug('joining result handler')
520
if threading.current_thread() is not result_handler:
521
result_handler.join(1e100)
523
if pool and hasattr(pool[0], 'terminate'):
524
debug('joining pool workers')
527
# worker has not yet exited
528
debug('cleaning up worker %d' % p.pid)
532
# Class whose instances are returned by `Pool.apply_async()`
535
class ApplyResult(object):
537
def __init__(self, cache, callback):
538
self._cond = threading.Condition(threading.Lock())
539
self._job = job_counter.next()
542
self._callback = callback
543
cache[self._job] = self
548
def successful(self):
552
def wait(self, timeout=None):
556
self._cond.wait(timeout)
560
def get(self, timeout=None):
569
def _set(self, i, obj):
570
self._success, self._value = obj
571
if self._callback and self._success:
572
self._callback(self._value)
579
del self._cache[self._job]
581
AsyncResult = ApplyResult # create alias -- see #17805
584
# Class whose instances are returned by `Pool.map_async()`
587
class MapResult(ApplyResult):
589
def __init__(self, cache, chunksize, length, callback):
590
ApplyResult.__init__(self, cache, callback)
592
self._value = [None] * length
593
self._chunksize = chunksize
595
self._number_left = 0
599
self._number_left = length//chunksize + bool(length % chunksize)
601
def _set(self, i, success_result):
602
success, result = success_result
604
self._value[i*self._chunksize:(i+1)*self._chunksize] = result
605
self._number_left -= 1
606
if self._number_left == 0:
608
self._callback(self._value)
609
del self._cache[self._job]
618
self._success = False
620
del self._cache[self._job]
629
# Class whose instances are returned by `Pool.imap()`
632
class IMapIterator(object):
634
def __init__(self, cache):
635
self._cond = threading.Condition(threading.Lock())
636
self._job = job_counter.next()
638
self._items = collections.deque()
642
cache[self._job] = self
647
def next(self, timeout=None):
651
item = self._items.popleft()
653
if self._index == self._length:
655
self._cond.wait(timeout)
657
item = self._items.popleft()
659
if self._index == self._length:
665
success, value = item
670
__next__ = next # XXX
672
def _set(self, i, obj):
676
self._items.append(obj)
678
while self._index in self._unsorted:
679
obj = self._unsorted.pop(self._index)
680
self._items.append(obj)
684
self._unsorted[i] = obj
686
if self._index == self._length:
687
del self._cache[self._job]
691
def _set_length(self, length):
694
self._length = length
695
if self._index == self._length:
697
del self._cache[self._job]
702
# Class whose instances are returned by `Pool.imap_unordered()`
705
class IMapUnorderedIterator(IMapIterator):
707
def _set(self, i, obj):
710
self._items.append(obj)
713
if self._index == self._length:
714
del self._cache[self._job]
722
class ThreadPool(Pool):
724
from .dummy import Process
726
def __init__(self, processes=None, initializer=None, initargs=()):
727
Pool.__init__(self, processes, initializer, initargs)
729
def _setup_queues(self):
730
self._inqueue = Queue.Queue()
731
self._outqueue = Queue.Queue()
732
self._quick_put = self._inqueue.put
733
self._quick_get = self._outqueue.get
736
def _help_stuff_finish(inqueue, task_handler, size):
737
# put sentinels at head of inqueue to make workers finish
738
inqueue.not_empty.acquire()
740
inqueue.queue.clear()
741
inqueue.queue.extend([None] * size)
742
inqueue.not_empty.notify_all()
744
inqueue.not_empty.release()