blob: 0c29e644ffd42832677f1e0e6ed933e20610a95a [file] [log] [blame]
Benjamin Petersone711caf2008-06-11 16:44:04 +00001#
2# Module providing the `Pool` class for managing a process pool
3#
4# multiprocessing/pool.py
5#
R. David Murray3fc969a2010-12-14 01:38:16 +00006# Copyright (c) 2006-2008, R Oudkerk
7# All rights reserved.
8#
9# Redistribution and use in source and binary forms, with or without
10# modification, are permitted provided that the following conditions
11# are met:
12#
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.
21#
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
32# SUCH DAMAGE.
Benjamin Petersone711caf2008-06-11 16:44:04 +000033#
34
35__all__ = ['Pool']
36
37#
38# Imports
39#
40
41import threading
42import queue
43import itertools
44import collections
45import time
46
47from multiprocessing import Process, cpu_count, TimeoutError
48from multiprocessing.util import Finalize, debug
49
50#
51# Constants representing the state of a pool
52#
53
54RUN = 0
55CLOSE = 1
56TERMINATE = 2
57
58#
59# Miscellaneous
60#
61
62job_counter = itertools.count()
63
64def mapstar(args):
65 return list(map(*args))
66
67#
68# Code run by worker processes
69#
70
Ask Solem2afcbf22010-11-09 20:55:52 +000071class MaybeEncodingError(Exception):
72 """Wraps possible unpickleable errors, so they can be
73 safely sent through the socket."""
74
75 def __init__(self, exc, value):
76 self.exc = repr(exc)
77 self.value = repr(value)
78 super(MaybeEncodingError, self).__init__(self.exc, self.value)
79
80 def __str__(self):
81 return "Error sending result: '%s'. Reason: '%s'" % (self.value,
82 self.exc)
83
84 def __repr__(self):
85 return "<MaybeEncodingError: %s>" % str(self)
86
87
Jesse Noller1f0b6582010-01-27 03:36:01 +000088def worker(inqueue, outqueue, initializer=None, initargs=(), maxtasks=None):
89 assert maxtasks is None or (type(maxtasks) == int and maxtasks > 0)
Benjamin Petersone711caf2008-06-11 16:44:04 +000090 put = outqueue.put
91 get = inqueue.get
92 if hasattr(inqueue, '_writer'):
93 inqueue._writer.close()
94 outqueue._reader.close()
95
96 if initializer is not None:
97 initializer(*initargs)
98
Jesse Noller1f0b6582010-01-27 03:36:01 +000099 completed = 0
100 while maxtasks is None or (maxtasks and completed < maxtasks):
Benjamin Petersone711caf2008-06-11 16:44:04 +0000101 try:
102 task = get()
103 except (EOFError, IOError):
104 debug('worker got EOFError or IOError -- exiting')
105 break
106
107 if task is None:
108 debug('worker got sentinel -- exiting')
109 break
110
111 job, i, func, args, kwds = task
112 try:
113 result = (True, func(*args, **kwds))
114 except Exception as e:
115 result = (False, e)
Ask Solem2afcbf22010-11-09 20:55:52 +0000116 try:
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" % (
121 wrapped))
122 put((job, i, (False, wrapped)))
Jesse Noller1f0b6582010-01-27 03:36:01 +0000123 completed += 1
124 debug('worker exiting after %d tasks' % completed)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000125
126#
127# Class representing a process pool
128#
129
130class Pool(object):
131 '''
Georg Brandl92905032008-11-22 08:51:39 +0000132 Class which supports an async version of applying functions to arguments.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000133 '''
134 Process = Process
135
Jesse Noller1f0b6582010-01-27 03:36:01 +0000136 def __init__(self, processes=None, initializer=None, initargs=(),
137 maxtasksperchild=None):
Benjamin Petersone711caf2008-06-11 16:44:04 +0000138 self._setup_queues()
139 self._taskqueue = queue.Queue()
140 self._cache = {}
141 self._state = RUN
Jesse Noller1f0b6582010-01-27 03:36:01 +0000142 self._maxtasksperchild = maxtasksperchild
143 self._initializer = initializer
144 self._initargs = initargs
Benjamin Petersone711caf2008-06-11 16:44:04 +0000145
146 if processes is None:
147 try:
148 processes = cpu_count()
149 except NotImplementedError:
150 processes = 1
Victor Stinner2fae27b2011-06-20 17:53:35 +0200151 if processes < 1:
152 raise ValueError("Number of processes must be at least 1")
Benjamin Petersone711caf2008-06-11 16:44:04 +0000153
Florent Xicluna5d1155c2011-10-28 14:45:05 +0200154 if initializer is not None and not callable(initializer):
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000155 raise TypeError('initializer must be a callable')
156
Jesse Noller1f0b6582010-01-27 03:36:01 +0000157 self._processes = processes
Benjamin Petersone711caf2008-06-11 16:44:04 +0000158 self._pool = []
Jesse Noller1f0b6582010-01-27 03:36:01 +0000159 self._repopulate_pool()
160
161 self._worker_handler = threading.Thread(
162 target=Pool._handle_workers,
163 args=(self, )
164 )
165 self._worker_handler.daemon = True
166 self._worker_handler._state = RUN
167 self._worker_handler.start()
168
Benjamin Petersone711caf2008-06-11 16:44:04 +0000169
170 self._task_handler = threading.Thread(
171 target=Pool._handle_tasks,
172 args=(self._taskqueue, self._quick_put, self._outqueue, self._pool)
173 )
Benjamin Petersonfae4c622008-08-18 18:40:08 +0000174 self._task_handler.daemon = True
Benjamin Petersone711caf2008-06-11 16:44:04 +0000175 self._task_handler._state = RUN
176 self._task_handler.start()
177
178 self._result_handler = threading.Thread(
179 target=Pool._handle_results,
180 args=(self._outqueue, self._quick_get, self._cache)
181 )
Benjamin Petersonfae4c622008-08-18 18:40:08 +0000182 self._result_handler.daemon = True
Benjamin Petersone711caf2008-06-11 16:44:04 +0000183 self._result_handler._state = RUN
184 self._result_handler.start()
185
186 self._terminate = Finalize(
187 self, self._terminate_pool,
188 args=(self._taskqueue, self._inqueue, self._outqueue, self._pool,
Jesse Noller1f0b6582010-01-27 03:36:01 +0000189 self._worker_handler, self._task_handler,
190 self._result_handler, self._cache),
Benjamin Petersone711caf2008-06-11 16:44:04 +0000191 exitpriority=15
192 )
193
Jesse Noller1f0b6582010-01-27 03:36:01 +0000194 def _join_exited_workers(self):
195 """Cleanup after any worker processes which have exited due to reaching
196 their specified lifetime. Returns True if any workers were cleaned up.
197 """
198 cleaned = False
199 for i in reversed(range(len(self._pool))):
200 worker = self._pool[i]
201 if worker.exitcode is not None:
202 # worker exited
203 debug('cleaning up worker %d' % i)
204 worker.join()
205 cleaned = True
206 del self._pool[i]
207 return cleaned
208
209 def _repopulate_pool(self):
210 """Bring the number of pool processes up to the specified number,
211 for use after reaping workers which have exited.
212 """
213 for i in range(self._processes - len(self._pool)):
214 w = self.Process(target=worker,
215 args=(self._inqueue, self._outqueue,
216 self._initializer,
217 self._initargs, self._maxtasksperchild)
218 )
219 self._pool.append(w)
220 w.name = w.name.replace('Process', 'PoolWorker')
221 w.daemon = True
222 w.start()
223 debug('added worker')
224
225 def _maintain_pool(self):
226 """Clean up any exited workers and start replacements for them.
227 """
228 if self._join_exited_workers():
229 self._repopulate_pool()
230
Benjamin Petersone711caf2008-06-11 16:44:04 +0000231 def _setup_queues(self):
232 from .queues import SimpleQueue
233 self._inqueue = SimpleQueue()
234 self._outqueue = SimpleQueue()
235 self._quick_put = self._inqueue._writer.send
236 self._quick_get = self._outqueue._reader.recv
237
238 def apply(self, func, args=(), kwds={}):
239 '''
Georg Brandl92905032008-11-22 08:51:39 +0000240 Equivalent of `func(*args, **kwds)`.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000241 '''
242 assert self._state == RUN
243 return self.apply_async(func, args, kwds).get()
244
245 def map(self, func, iterable, chunksize=None):
246 '''
Georg Brandl92905032008-11-22 08:51:39 +0000247 Apply `func` to each element in `iterable`, collecting the results
248 in a list that is returned.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000249 '''
250 assert self._state == RUN
251 return self.map_async(func, iterable, chunksize).get()
252
253 def imap(self, func, iterable, chunksize=1):
254 '''
Georg Brandl92905032008-11-22 08:51:39 +0000255 Equivalent of `map()` -- can be MUCH slower than `Pool.map()`.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000256 '''
257 assert self._state == RUN
258 if chunksize == 1:
259 result = IMapIterator(self._cache)
260 self._taskqueue.put((((result._job, i, func, (x,), {})
261 for i, x in enumerate(iterable)), result._set_length))
262 return result
263 else:
264 assert chunksize > 1
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)
270
271 def imap_unordered(self, func, iterable, chunksize=1):
272 '''
Georg Brandl92905032008-11-22 08:51:39 +0000273 Like `imap()` method but ordering of results is arbitrary.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000274 '''
275 assert self._state == RUN
276 if chunksize == 1:
277 result = IMapUnorderedIterator(self._cache)
278 self._taskqueue.put((((result._job, i, func, (x,), {})
279 for i, x in enumerate(iterable)), result._set_length))
280 return result
281 else:
282 assert chunksize > 1
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)
288
Ask Solem2afcbf22010-11-09 20:55:52 +0000289 def apply_async(self, func, args=(), kwds={}, callback=None,
290 error_callback=None):
Benjamin Petersone711caf2008-06-11 16:44:04 +0000291 '''
Georg Brandl92905032008-11-22 08:51:39 +0000292 Asynchronous version of `apply()` method.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000293 '''
294 assert self._state == RUN
Ask Solem2afcbf22010-11-09 20:55:52 +0000295 result = ApplyResult(self._cache, callback, error_callback)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000296 self._taskqueue.put(([(result._job, None, func, args, kwds)], None))
297 return result
298
Ask Solem2afcbf22010-11-09 20:55:52 +0000299 def map_async(self, func, iterable, chunksize=None, callback=None,
300 error_callback=None):
Benjamin Petersone711caf2008-06-11 16:44:04 +0000301 '''
Georg Brandl92905032008-11-22 08:51:39 +0000302 Asynchronous version of `map()` method.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000303 '''
304 assert self._state == RUN
305 if not hasattr(iterable, '__len__'):
306 iterable = list(iterable)
307
308 if chunksize is None:
309 chunksize, extra = divmod(len(iterable), len(self._pool) * 4)
310 if extra:
311 chunksize += 1
Alexandre Vassalottie52e3782009-07-17 09:18:18 +0000312 if len(iterable) == 0:
313 chunksize = 0
Benjamin Petersone711caf2008-06-11 16:44:04 +0000314
315 task_batches = Pool._get_tasks(func, iterable, chunksize)
Ask Solem2afcbf22010-11-09 20:55:52 +0000316 result = MapResult(self._cache, chunksize, len(iterable), callback,
317 error_callback=error_callback)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000318 self._taskqueue.put((((result._job, i, mapstar, (x,), {})
319 for i, x in enumerate(task_batches)), None))
320 return result
321
322 @staticmethod
Jesse Noller1f0b6582010-01-27 03:36:01 +0000323 def _handle_workers(pool):
Charles-François Natalif8859e12011-10-24 18:45:29 +0200324 thread = threading.current_thread()
325
326 # Keep maintaining workers until the cache gets drained, unless the pool
327 # is terminated.
328 while thread._state == RUN or (pool._cache and thread._state != TERMINATE):
Jesse Noller1f0b6582010-01-27 03:36:01 +0000329 pool._maintain_pool()
330 time.sleep(0.1)
Antoine Pitrou81dee6b2011-04-11 00:18:59 +0200331 # send sentinel to stop workers
332 pool._taskqueue.put(None)
Jesse Noller1f0b6582010-01-27 03:36:01 +0000333 debug('worker handler exiting')
334
335 @staticmethod
Benjamin Petersone711caf2008-06-11 16:44:04 +0000336 def _handle_tasks(taskqueue, put, outqueue, pool):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000337 thread = threading.current_thread()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000338
339 for taskseq, set_length in iter(taskqueue.get, None):
340 i = -1
341 for i, task in enumerate(taskseq):
342 if thread._state:
343 debug('task handler found thread._state != RUN')
344 break
345 try:
346 put(task)
347 except IOError:
348 debug('could not put task on queue')
349 break
350 else:
351 if set_length:
352 debug('doing set_length()')
353 set_length(i+1)
354 continue
355 break
356 else:
357 debug('task handler got sentinel')
358
359
360 try:
361 # tell result handler to finish when cache is empty
362 debug('task handler sending sentinel to result handler')
363 outqueue.put(None)
364
365 # tell workers there is no more work
366 debug('task handler sending sentinel to workers')
367 for p in pool:
368 put(None)
369 except IOError:
370 debug('task handler got IOError when sending sentinels')
371
372 debug('task handler exiting')
373
374 @staticmethod
375 def _handle_results(outqueue, get, cache):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000376 thread = threading.current_thread()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000377
378 while 1:
379 try:
380 task = get()
381 except (IOError, EOFError):
382 debug('result handler got EOFError/IOError -- exiting')
383 return
384
385 if thread._state:
386 assert thread._state == TERMINATE
387 debug('result handler found thread._state=TERMINATE')
388 break
389
390 if task is None:
391 debug('result handler got sentinel')
392 break
393
394 job, i, obj = task
395 try:
396 cache[job]._set(i, obj)
397 except KeyError:
398 pass
399
400 while cache and thread._state != TERMINATE:
401 try:
402 task = get()
403 except (IOError, EOFError):
404 debug('result handler got EOFError/IOError -- exiting')
405 return
406
407 if task is None:
408 debug('result handler ignoring extra sentinel')
409 continue
410 job, i, obj = task
411 try:
412 cache[job]._set(i, obj)
413 except KeyError:
414 pass
415
416 if hasattr(outqueue, '_reader'):
417 debug('ensuring that outqueue is not full')
418 # If we don't make room available in outqueue then
419 # attempts to add the sentinel (None) to outqueue may
420 # block. There is guaranteed to be no more than 2 sentinels.
421 try:
422 for i in range(10):
423 if not outqueue._reader.poll():
424 break
425 get()
426 except (IOError, EOFError):
427 pass
428
429 debug('result handler exiting: len(cache)=%s, thread._state=%s',
430 len(cache), thread._state)
431
432 @staticmethod
433 def _get_tasks(func, it, size):
434 it = iter(it)
435 while 1:
436 x = tuple(itertools.islice(it, size))
437 if not x:
438 return
439 yield (func, x)
440
441 def __reduce__(self):
442 raise NotImplementedError(
443 'pool objects cannot be passed between processes or pickled'
444 )
445
446 def close(self):
447 debug('closing pool')
448 if self._state == RUN:
449 self._state = CLOSE
Jesse Noller1f0b6582010-01-27 03:36:01 +0000450 self._worker_handler._state = CLOSE
Benjamin Petersone711caf2008-06-11 16:44:04 +0000451
452 def terminate(self):
453 debug('terminating pool')
454 self._state = TERMINATE
Jesse Noller1f0b6582010-01-27 03:36:01 +0000455 self._worker_handler._state = TERMINATE
Benjamin Petersone711caf2008-06-11 16:44:04 +0000456 self._terminate()
457
458 def join(self):
459 debug('joining pool')
460 assert self._state in (CLOSE, TERMINATE)
Jesse Noller1f0b6582010-01-27 03:36:01 +0000461 self._worker_handler.join()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000462 self._task_handler.join()
463 self._result_handler.join()
464 for p in self._pool:
465 p.join()
466
467 @staticmethod
468 def _help_stuff_finish(inqueue, task_handler, size):
469 # task_handler may be blocked trying to put items on inqueue
470 debug('removing tasks from inqueue until task handler finished')
471 inqueue._rlock.acquire()
Benjamin Peterson672b8032008-06-11 19:14:14 +0000472 while task_handler.is_alive() and inqueue._reader.poll():
Benjamin Petersone711caf2008-06-11 16:44:04 +0000473 inqueue._reader.recv()
474 time.sleep(0)
475
476 @classmethod
477 def _terminate_pool(cls, taskqueue, inqueue, outqueue, pool,
Jesse Noller1f0b6582010-01-27 03:36:01 +0000478 worker_handler, task_handler, result_handler, cache):
Benjamin Petersone711caf2008-06-11 16:44:04 +0000479 # this is guaranteed to only be called once
480 debug('finalizing pool')
481
Jesse Noller1f0b6582010-01-27 03:36:01 +0000482 worker_handler._state = TERMINATE
Benjamin Petersone711caf2008-06-11 16:44:04 +0000483 task_handler._state = TERMINATE
Benjamin Petersone711caf2008-06-11 16:44:04 +0000484
485 debug('helping task handler/workers to finish')
486 cls._help_stuff_finish(inqueue, task_handler, len(pool))
487
Benjamin Peterson672b8032008-06-11 19:14:14 +0000488 assert result_handler.is_alive() or len(cache) == 0
Benjamin Petersone711caf2008-06-11 16:44:04 +0000489
490 result_handler._state = TERMINATE
491 outqueue.put(None) # sentinel
492
Antoine Pitrou81dee6b2011-04-11 00:18:59 +0200493 # We must wait for the worker handler to exit before terminating
494 # workers because we don't want workers to be restarted behind our back.
495 debug('joining worker handler')
496 worker_handler.join()
497
Jesse Noller1f0b6582010-01-27 03:36:01 +0000498 # Terminate workers which haven't already finished.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000499 if pool and hasattr(pool[0], 'terminate'):
500 debug('terminating workers')
501 for p in pool:
Jesse Noller1f0b6582010-01-27 03:36:01 +0000502 if p.exitcode is None:
503 p.terminate()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000504
505 debug('joining task handler')
Antoine Pitrou7c3e5772010-04-14 15:44:10 +0000506 task_handler.join()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000507
508 debug('joining result handler')
Antoine Pitroubed9a5b2011-04-11 00:20:23 +0200509 result_handler.join()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000510
511 if pool and hasattr(pool[0], 'terminate'):
512 debug('joining pool workers')
513 for p in pool:
Florent Xicluna998171f2010-03-08 13:32:17 +0000514 if p.is_alive():
Jesse Noller1f0b6582010-01-27 03:36:01 +0000515 # worker has not yet exited
Florent Xicluna998171f2010-03-08 13:32:17 +0000516 debug('cleaning up worker %d' % p.pid)
517 p.join()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000518
519#
520# Class whose instances are returned by `Pool.apply_async()`
521#
522
523class ApplyResult(object):
524
Ask Solem2afcbf22010-11-09 20:55:52 +0000525 def __init__(self, cache, callback, error_callback):
Benjamin Petersone711caf2008-06-11 16:44:04 +0000526 self._cond = threading.Condition(threading.Lock())
527 self._job = next(job_counter)
528 self._cache = cache
529 self._ready = False
530 self._callback = callback
Ask Solem2afcbf22010-11-09 20:55:52 +0000531 self._error_callback = error_callback
Benjamin Petersone711caf2008-06-11 16:44:04 +0000532 cache[self._job] = self
533
534 def ready(self):
535 return self._ready
536
537 def successful(self):
538 assert self._ready
539 return self._success
540
541 def wait(self, timeout=None):
542 self._cond.acquire()
543 try:
544 if not self._ready:
545 self._cond.wait(timeout)
546 finally:
547 self._cond.release()
548
549 def get(self, timeout=None):
550 self.wait(timeout)
551 if not self._ready:
552 raise TimeoutError
553 if self._success:
554 return self._value
555 else:
556 raise self._value
557
558 def _set(self, i, obj):
559 self._success, self._value = obj
560 if self._callback and self._success:
561 self._callback(self._value)
Ask Solem2afcbf22010-11-09 20:55:52 +0000562 if self._error_callback and not self._success:
563 self._error_callback(self._value)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000564 self._cond.acquire()
565 try:
566 self._ready = True
567 self._cond.notify()
568 finally:
569 self._cond.release()
570 del self._cache[self._job]
571
572#
573# Class whose instances are returned by `Pool.map_async()`
574#
575
576class MapResult(ApplyResult):
577
Ask Solem2afcbf22010-11-09 20:55:52 +0000578 def __init__(self, cache, chunksize, length, callback, error_callback):
579 ApplyResult.__init__(self, cache, callback,
580 error_callback=error_callback)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000581 self._success = True
582 self._value = [None] * length
583 self._chunksize = chunksize
584 if chunksize <= 0:
585 self._number_left = 0
586 self._ready = True
587 else:
588 self._number_left = length//chunksize + bool(length % chunksize)
589
590 def _set(self, i, success_result):
591 success, result = success_result
592 if success:
593 self._value[i*self._chunksize:(i+1)*self._chunksize] = result
594 self._number_left -= 1
595 if self._number_left == 0:
596 if self._callback:
597 self._callback(self._value)
598 del self._cache[self._job]
599 self._cond.acquire()
600 try:
601 self._ready = True
602 self._cond.notify()
603 finally:
604 self._cond.release()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000605 else:
606 self._success = False
607 self._value = result
Ask Solem2afcbf22010-11-09 20:55:52 +0000608 if self._error_callback:
609 self._error_callback(self._value)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000610 del self._cache[self._job]
611 self._cond.acquire()
612 try:
613 self._ready = True
614 self._cond.notify()
615 finally:
616 self._cond.release()
617
618#
619# Class whose instances are returned by `Pool.imap()`
620#
621
622class IMapIterator(object):
623
624 def __init__(self, cache):
625 self._cond = threading.Condition(threading.Lock())
626 self._job = next(job_counter)
627 self._cache = cache
628 self._items = collections.deque()
629 self._index = 0
630 self._length = None
631 self._unsorted = {}
632 cache[self._job] = self
633
634 def __iter__(self):
635 return self
636
637 def next(self, timeout=None):
638 self._cond.acquire()
639 try:
640 try:
641 item = self._items.popleft()
642 except IndexError:
643 if self._index == self._length:
644 raise StopIteration
645 self._cond.wait(timeout)
646 try:
647 item = self._items.popleft()
648 except IndexError:
649 if self._index == self._length:
650 raise StopIteration
651 raise TimeoutError
652 finally:
653 self._cond.release()
654
655 success, value = item
656 if success:
657 return value
658 raise value
659
660 __next__ = next # XXX
661
662 def _set(self, i, obj):
663 self._cond.acquire()
664 try:
665 if self._index == i:
666 self._items.append(obj)
667 self._index += 1
668 while self._index in self._unsorted:
669 obj = self._unsorted.pop(self._index)
670 self._items.append(obj)
671 self._index += 1
672 self._cond.notify()
673 else:
674 self._unsorted[i] = obj
675
676 if self._index == self._length:
677 del self._cache[self._job]
678 finally:
679 self._cond.release()
680
681 def _set_length(self, length):
682 self._cond.acquire()
683 try:
684 self._length = length
685 if self._index == self._length:
686 self._cond.notify()
687 del self._cache[self._job]
688 finally:
689 self._cond.release()
690
691#
692# Class whose instances are returned by `Pool.imap_unordered()`
693#
694
695class IMapUnorderedIterator(IMapIterator):
696
697 def _set(self, i, obj):
698 self._cond.acquire()
699 try:
700 self._items.append(obj)
701 self._index += 1
702 self._cond.notify()
703 if self._index == self._length:
704 del self._cache[self._job]
705 finally:
706 self._cond.release()
707
708#
709#
710#
711
712class ThreadPool(Pool):
713
714 from .dummy import Process
715
716 def __init__(self, processes=None, initializer=None, initargs=()):
717 Pool.__init__(self, processes, initializer, initargs)
718
719 def _setup_queues(self):
720 self._inqueue = queue.Queue()
721 self._outqueue = queue.Queue()
722 self._quick_put = self._inqueue.put
723 self._quick_get = self._outqueue.get
724
725 @staticmethod
726 def _help_stuff_finish(inqueue, task_handler, size):
727 # put sentinels at head of inqueue to make workers finish
728 inqueue.not_empty.acquire()
729 try:
730 inqueue.queue.clear()
731 inqueue.queue.extend([None] * size)
Benjamin Peterson672b8032008-06-11 19:14:14 +0000732 inqueue.not_empty.notify_all()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000733 finally:
734 inqueue.not_empty.release()