blob: 04531b91bd23c314d18ddffd26d202f533719ae2 [file] [log] [blame]
Benjamin Peterson7f03ea72008-06-13 19:20:48 +00001#
2# Module providing the `Pool` class for managing a process pool
3#
4# multiprocessing/pool.py
5#
R. David Murray79af2452010-12-14 01:42:40 +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 Peterson7f03ea72008-06-13 19:20:48 +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 map(*args)
66
67#
68# Code run by worker processes
69#
70
Richard Oudkerk0c200c22012-05-02 16:36:26 +010071class 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 Noller654ade32010-01-27 03:05:57 +000088def worker(inqueue, outqueue, initializer=None, initargs=(), maxtasks=None):
89 assert maxtasks is None or (type(maxtasks) == int and maxtasks > 0)
Benjamin Peterson7f03ea72008-06-13 19:20:48 +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 Noller654ade32010-01-27 03:05:57 +000099 completed = 0
100 while maxtasks is None or (maxtasks and completed < maxtasks):
Benjamin Peterson7f03ea72008-06-13 19:20:48 +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, e:
115 result = (False, e)
Richard Oudkerk0c200c22012-05-02 16:36:26 +0100116 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 Noller654ade32010-01-27 03:05:57 +0000123 completed += 1
124 debug('worker exiting after %d tasks' % completed)
Benjamin Peterson7f03ea72008-06-13 19:20:48 +0000125
126#
127# Class representing a process pool
128#
129
130class Pool(object):
131 '''
132 Class which supports an async version of the `apply()` builtin
133 '''
134 Process = Process
135
Jesse Noller654ade32010-01-27 03:05:57 +0000136 def __init__(self, processes=None, initializer=None, initargs=(),
137 maxtasksperchild=None):
Benjamin Peterson7f03ea72008-06-13 19:20:48 +0000138 self._setup_queues()
139 self._taskqueue = Queue.Queue()
140 self._cache = {}
141 self._state = RUN
Jesse Noller654ade32010-01-27 03:05:57 +0000142 self._maxtasksperchild = maxtasksperchild
143 self._initializer = initializer
144 self._initargs = initargs
Benjamin Peterson7f03ea72008-06-13 19:20:48 +0000145
146 if processes is None:
147 try:
148 processes = cpu_count()
149 except NotImplementedError:
150 processes = 1
Victor Stinnerf64a0cf2011-06-20 17:54:33 +0200151 if processes < 1:
152 raise ValueError("Number of processes must be at least 1")
Benjamin Peterson7f03ea72008-06-13 19:20:48 +0000153
Jesse Noller7152f6d2009-04-02 05:17:26 +0000154 if initializer is not None and not hasattr(initializer, '__call__'):
155 raise TypeError('initializer must be a callable')
156
Jesse Noller654ade32010-01-27 03:05:57 +0000157 self._processes = processes
Benjamin Peterson7f03ea72008-06-13 19:20:48 +0000158 self._pool = []
Jesse Noller654ade32010-01-27 03:05:57 +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 Peterson7f03ea72008-06-13 19:20:48 +0000169
170 self._task_handler = threading.Thread(
171 target=Pool._handle_tasks,
Richard Oudkerk21aad972013-10-28 23:02:22 +0000172 args=(self._taskqueue, self._quick_put, self._outqueue,
173 self._pool, self._cache)
Benjamin Peterson7f03ea72008-06-13 19:20:48 +0000174 )
Benjamin Peterson82aa2012008-08-18 18:31:58 +0000175 self._task_handler.daemon = True
Benjamin Peterson7f03ea72008-06-13 19:20:48 +0000176 self._task_handler._state = RUN
177 self._task_handler.start()
178
179 self._result_handler = threading.Thread(
180 target=Pool._handle_results,
181 args=(self._outqueue, self._quick_get, self._cache)
182 )
Benjamin Peterson82aa2012008-08-18 18:31:58 +0000183 self._result_handler.daemon = True
Benjamin Peterson7f03ea72008-06-13 19:20:48 +0000184 self._result_handler._state = RUN
185 self._result_handler.start()
186
187 self._terminate = Finalize(
188 self, self._terminate_pool,
189 args=(self._taskqueue, self._inqueue, self._outqueue, self._pool,
Jesse Noller654ade32010-01-27 03:05:57 +0000190 self._worker_handler, self._task_handler,
191 self._result_handler, self._cache),
Benjamin Peterson7f03ea72008-06-13 19:20:48 +0000192 exitpriority=15
193 )
194
Jesse Noller654ade32010-01-27 03:05:57 +0000195 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.
198 """
199 cleaned = False
200 for i in reversed(range(len(self._pool))):
201 worker = self._pool[i]
202 if worker.exitcode is not None:
203 # worker exited
204 debug('cleaning up worker %d' % i)
205 worker.join()
206 cleaned = True
207 del self._pool[i]
208 return cleaned
209
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.
213 """
214 for i in range(self._processes - len(self._pool)):
215 w = self.Process(target=worker,
216 args=(self._inqueue, self._outqueue,
217 self._initializer,
218 self._initargs, self._maxtasksperchild)
219 )
220 self._pool.append(w)
221 w.name = w.name.replace('Process', 'PoolWorker')
222 w.daemon = True
223 w.start()
224 debug('added worker')
225
226 def _maintain_pool(self):
227 """Clean up any exited workers and start replacements for them.
228 """
229 if self._join_exited_workers():
230 self._repopulate_pool()
231
Benjamin Peterson7f03ea72008-06-13 19:20:48 +0000232 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
238
239 def apply(self, func, args=(), kwds={}):
240 '''
241 Equivalent of `apply()` builtin
242 '''
243 assert self._state == RUN
244 return self.apply_async(func, args, kwds).get()
245
246 def map(self, func, iterable, chunksize=None):
247 '''
248 Equivalent of `map()` builtin
249 '''
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 Brandl5ecd7452008-11-22 08:45:33 +0000255 Equivalent of `itertools.imap()` -- can be MUCH slower than `Pool.map()`
Benjamin Peterson7f03ea72008-06-13 19:20:48 +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 '''
273 Like `imap()` method but ordering of results is arbitrary
274 '''
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
289 def apply_async(self, func, args=(), kwds={}, callback=None):
290 '''
291 Asynchronous equivalent of `apply()` builtin
292 '''
293 assert self._state == RUN
294 result = ApplyResult(self._cache, callback)
295 self._taskqueue.put(([(result._job, None, func, args, kwds)], None))
296 return result
297
298 def map_async(self, func, iterable, chunksize=None, callback=None):
299 '''
300 Asynchronous equivalent of `map()` builtin
301 '''
302 assert self._state == RUN
303 if not hasattr(iterable, '__len__'):
304 iterable = list(iterable)
305
306 if chunksize is None:
307 chunksize, extra = divmod(len(iterable), len(self._pool) * 4)
308 if extra:
309 chunksize += 1
Jesse Noller7530e472009-07-16 14:23:04 +0000310 if len(iterable) == 0:
311 chunksize = 0
Benjamin Peterson7f03ea72008-06-13 19:20:48 +0000312
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))
317 return result
318
319 @staticmethod
Jesse Noller654ade32010-01-27 03:05:57 +0000320 def _handle_workers(pool):
Charles-François Natali46f990e2011-10-24 18:43:51 +0200321 thread = threading.current_thread()
322
323 # Keep maintaining workers until the cache gets drained, unless the pool
324 # is terminated.
325 while thread._state == RUN or (pool._cache and thread._state != TERMINATE):
Jesse Noller654ade32010-01-27 03:05:57 +0000326 pool._maintain_pool()
327 time.sleep(0.1)
Antoine Pitrou7dfc8742011-04-11 00:26:42 +0200328 # send sentinel to stop workers
329 pool._taskqueue.put(None)
Jesse Noller654ade32010-01-27 03:05:57 +0000330 debug('worker handler exiting')
331
332 @staticmethod
Richard Oudkerk21aad972013-10-28 23:02:22 +0000333 def _handle_tasks(taskqueue, put, outqueue, pool, cache):
Benjamin Peterson7f03ea72008-06-13 19:20:48 +0000334 thread = threading.current_thread()
335
336 for taskseq, set_length in iter(taskqueue.get, None):
337 i = -1
338 for i, task in enumerate(taskseq):
339 if thread._state:
340 debug('task handler found thread._state != RUN')
341 break
342 try:
343 put(task)
Richard Oudkerk21aad972013-10-28 23:02:22 +0000344 except Exception as e:
345 job, ind = task[:2]
346 try:
347 cache[job]._set(ind, (False, e))
348 except KeyError:
349 pass
Benjamin Peterson7f03ea72008-06-13 19:20:48 +0000350 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):
376 thread = threading.current_thread()
377
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 Noller654ade32010-01-27 03:05:57 +0000450 self._worker_handler._state = CLOSE
Benjamin Peterson7f03ea72008-06-13 19:20:48 +0000451
452 def terminate(self):
453 debug('terminating pool')
454 self._state = TERMINATE
Jesse Noller654ade32010-01-27 03:05:57 +0000455 self._worker_handler._state = TERMINATE
Benjamin Peterson7f03ea72008-06-13 19:20:48 +0000456 self._terminate()
457
458 def join(self):
459 debug('joining pool')
460 assert self._state in (CLOSE, TERMINATE)
Jesse Noller654ade32010-01-27 03:05:57 +0000461 self._worker_handler.join()
Benjamin Peterson7f03ea72008-06-13 19:20:48 +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()
472 while task_handler.is_alive() and inqueue._reader.poll():
473 inqueue._reader.recv()
474 time.sleep(0)
475
476 @classmethod
477 def _terminate_pool(cls, taskqueue, inqueue, outqueue, pool,
Jesse Noller654ade32010-01-27 03:05:57 +0000478 worker_handler, task_handler, result_handler, cache):
Benjamin Peterson7f03ea72008-06-13 19:20:48 +0000479 # this is guaranteed to only be called once
480 debug('finalizing pool')
481
Jesse Noller654ade32010-01-27 03:05:57 +0000482 worker_handler._state = TERMINATE
Benjamin Peterson7f03ea72008-06-13 19:20:48 +0000483 task_handler._state = TERMINATE
Benjamin Peterson7f03ea72008-06-13 19:20:48 +0000484
485 debug('helping task handler/workers to finish')
486 cls._help_stuff_finish(inqueue, task_handler, len(pool))
487
488 assert result_handler.is_alive() or len(cache) == 0
489
490 result_handler._state = TERMINATE
491 outqueue.put(None) # sentinel
492
Antoine Pitrou7dfc8742011-04-11 00:26:42 +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')
Richard Oudkerk4215d272012-06-18 15:37:31 +0100496 if threading.current_thread() is not worker_handler:
497 worker_handler.join(1e100)
Antoine Pitrou7dfc8742011-04-11 00:26:42 +0200498
Jesse Noller654ade32010-01-27 03:05:57 +0000499 # Terminate workers which haven't already finished.
Benjamin Peterson7f03ea72008-06-13 19:20:48 +0000500 if pool and hasattr(pool[0], 'terminate'):
501 debug('terminating workers')
502 for p in pool:
Jesse Noller654ade32010-01-27 03:05:57 +0000503 if p.exitcode is None:
504 p.terminate()
Benjamin Peterson7f03ea72008-06-13 19:20:48 +0000505
506 debug('joining task handler')
Richard Oudkerk4215d272012-06-18 15:37:31 +0100507 if threading.current_thread() is not task_handler:
508 task_handler.join(1e100)
Benjamin Peterson7f03ea72008-06-13 19:20:48 +0000509
510 debug('joining result handler')
Richard Oudkerk4215d272012-06-18 15:37:31 +0100511 if threading.current_thread() is not result_handler:
512 result_handler.join(1e100)
Benjamin Peterson7f03ea72008-06-13 19:20:48 +0000513
514 if pool and hasattr(pool[0], 'terminate'):
515 debug('joining pool workers')
516 for p in pool:
Florent Xiclunad034b322010-03-08 11:01:39 +0000517 if p.is_alive():
Jesse Noller654ade32010-01-27 03:05:57 +0000518 # worker has not yet exited
Florent Xiclunad034b322010-03-08 11:01:39 +0000519 debug('cleaning up worker %d' % p.pid)
520 p.join()
Benjamin Peterson7f03ea72008-06-13 19:20:48 +0000521
522#
523# Class whose instances are returned by `Pool.apply_async()`
524#
525
526class ApplyResult(object):
527
528 def __init__(self, cache, callback):
529 self._cond = threading.Condition(threading.Lock())
530 self._job = job_counter.next()
531 self._cache = cache
532 self._ready = False
533 self._callback = callback
534 cache[self._job] = self
535
536 def ready(self):
537 return self._ready
538
539 def successful(self):
540 assert self._ready
541 return self._success
542
543 def wait(self, timeout=None):
544 self._cond.acquire()
545 try:
546 if not self._ready:
547 self._cond.wait(timeout)
548 finally:
549 self._cond.release()
550
551 def get(self, timeout=None):
552 self.wait(timeout)
553 if not self._ready:
554 raise TimeoutError
555 if self._success:
556 return self._value
557 else:
558 raise self._value
559
560 def _set(self, i, obj):
561 self._success, self._value = obj
562 if self._callback and self._success:
563 self._callback(self._value)
564 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
Richard Oudkerka9b90a72013-05-06 12:04:28 +0100572AsyncResult = ApplyResult # create alias -- see #17805
573
Benjamin Peterson7f03ea72008-06-13 19:20:48 +0000574#
575# Class whose instances are returned by `Pool.map_async()`
576#
577
578class MapResult(ApplyResult):
579
580 def __init__(self, cache, chunksize, length, callback):
581 ApplyResult.__init__(self, cache, callback)
582 self._success = True
583 self._value = [None] * length
584 self._chunksize = chunksize
585 if chunksize <= 0:
586 self._number_left = 0
587 self._ready = True
Richard Oudkerkd44a4a22012-06-06 17:52:18 +0100588 del cache[self._job]
Benjamin Peterson7f03ea72008-06-13 19:20:48 +0000589 else:
590 self._number_left = length//chunksize + bool(length % chunksize)
591
592 def _set(self, i, success_result):
593 success, result = success_result
594 if success:
595 self._value[i*self._chunksize:(i+1)*self._chunksize] = result
596 self._number_left -= 1
597 if self._number_left == 0:
598 if self._callback:
599 self._callback(self._value)
600 del self._cache[self._job]
601 self._cond.acquire()
602 try:
603 self._ready = True
604 self._cond.notify()
605 finally:
606 self._cond.release()
607
608 else:
609 self._success = False
610 self._value = result
611 del self._cache[self._job]
612 self._cond.acquire()
613 try:
614 self._ready = True
615 self._cond.notify()
616 finally:
617 self._cond.release()
618
619#
620# Class whose instances are returned by `Pool.imap()`
621#
622
623class IMapIterator(object):
624
625 def __init__(self, cache):
626 self._cond = threading.Condition(threading.Lock())
627 self._job = job_counter.next()
628 self._cache = cache
629 self._items = collections.deque()
630 self._index = 0
631 self._length = None
632 self._unsorted = {}
633 cache[self._job] = self
634
635 def __iter__(self):
636 return self
637
638 def next(self, timeout=None):
639 self._cond.acquire()
640 try:
641 try:
642 item = self._items.popleft()
643 except IndexError:
644 if self._index == self._length:
645 raise StopIteration
646 self._cond.wait(timeout)
647 try:
648 item = self._items.popleft()
649 except IndexError:
650 if self._index == self._length:
651 raise StopIteration
652 raise TimeoutError
653 finally:
654 self._cond.release()
655
656 success, value = item
657 if success:
658 return value
659 raise value
660
661 __next__ = next # XXX
662
663 def _set(self, i, obj):
664 self._cond.acquire()
665 try:
666 if self._index == i:
667 self._items.append(obj)
668 self._index += 1
669 while self._index in self._unsorted:
670 obj = self._unsorted.pop(self._index)
671 self._items.append(obj)
672 self._index += 1
673 self._cond.notify()
674 else:
675 self._unsorted[i] = obj
676
677 if self._index == self._length:
678 del self._cache[self._job]
679 finally:
680 self._cond.release()
681
682 def _set_length(self, length):
683 self._cond.acquire()
684 try:
685 self._length = length
686 if self._index == self._length:
687 self._cond.notify()
688 del self._cache[self._job]
689 finally:
690 self._cond.release()
691
692#
693# Class whose instances are returned by `Pool.imap_unordered()`
694#
695
696class IMapUnorderedIterator(IMapIterator):
697
698 def _set(self, i, obj):
699 self._cond.acquire()
700 try:
701 self._items.append(obj)
702 self._index += 1
703 self._cond.notify()
704 if self._index == self._length:
705 del self._cache[self._job]
706 finally:
707 self._cond.release()
708
709#
710#
711#
712
713class ThreadPool(Pool):
714
715 from .dummy import Process
716
717 def __init__(self, processes=None, initializer=None, initargs=()):
718 Pool.__init__(self, processes, initializer, initargs)
719
720 def _setup_queues(self):
721 self._inqueue = Queue.Queue()
722 self._outqueue = Queue.Queue()
723 self._quick_put = self._inqueue.put
724 self._quick_get = self._outqueue.get
725
726 @staticmethod
727 def _help_stuff_finish(inqueue, task_handler, size):
728 # put sentinels at head of inqueue to make workers finish
729 inqueue.not_empty.acquire()
730 try:
731 inqueue.queue.clear()
732 inqueue.queue.extend([None] * size)
733 inqueue.not_empty.notify_all()
734 finally:
735 inqueue.not_empty.release()