blob: 5c1805f73e9f925f9e6d9895f0f7c488f93ed2df [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#
6# Copyright (c) 2007-2008, R Oudkerk --- see COPYING.txt
7#
8
9__all__ = ['Pool']
10
11#
12# Imports
13#
14
15import threading
16import queue
17import itertools
18import collections
19import time
20
21from multiprocessing import Process, cpu_count, TimeoutError
22from multiprocessing.util import Finalize, debug
23
24#
25# Constants representing the state of a pool
26#
27
28RUN = 0
29CLOSE = 1
30TERMINATE = 2
31
32#
33# Miscellaneous
34#
35
36job_counter = itertools.count()
37
38def mapstar(args):
39 return list(map(*args))
40
41#
42# Code run by worker processes
43#
44
45def worker(inqueue, outqueue, initializer=None, initargs=()):
46 put = outqueue.put
47 get = inqueue.get
48 if hasattr(inqueue, '_writer'):
49 inqueue._writer.close()
50 outqueue._reader.close()
51
52 if initializer is not None:
53 initializer(*initargs)
54
55 while 1:
56 try:
57 task = get()
58 except (EOFError, IOError):
59 debug('worker got EOFError or IOError -- exiting')
60 break
61
62 if task is None:
63 debug('worker got sentinel -- exiting')
64 break
65
66 job, i, func, args, kwds = task
67 try:
68 result = (True, func(*args, **kwds))
69 except Exception as e:
70 result = (False, e)
71 put((job, i, result))
72
73#
74# Class representing a process pool
75#
76
77class Pool(object):
78 '''
Georg Brandl92905032008-11-22 08:51:39 +000079 Class which supports an async version of applying functions to arguments.
Benjamin Petersone711caf2008-06-11 16:44:04 +000080 '''
81 Process = Process
82
83 def __init__(self, processes=None, initializer=None, initargs=()):
84 self._setup_queues()
85 self._taskqueue = queue.Queue()
86 self._cache = {}
87 self._state = RUN
88
89 if processes is None:
90 try:
91 processes = cpu_count()
92 except NotImplementedError:
93 processes = 1
94
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +000095 if initializer is not None and not hasattr(initializer, '__call__'):
96 raise TypeError('initializer must be a callable')
97
Benjamin Petersone711caf2008-06-11 16:44:04 +000098 self._pool = []
99 for i in range(processes):
100 w = self.Process(
101 target=worker,
102 args=(self._inqueue, self._outqueue, initializer, initargs)
103 )
104 self._pool.append(w)
Benjamin Peterson58ea9fe2008-08-19 19:17:39 +0000105 w.name = w.name.replace('Process', 'PoolWorker')
Benjamin Petersonfae4c622008-08-18 18:40:08 +0000106 w.daemon = True
Benjamin Petersone711caf2008-06-11 16:44:04 +0000107 w.start()
108
109 self._task_handler = threading.Thread(
110 target=Pool._handle_tasks,
111 args=(self._taskqueue, self._quick_put, self._outqueue, self._pool)
112 )
Benjamin Petersonfae4c622008-08-18 18:40:08 +0000113 self._task_handler.daemon = True
Benjamin Petersone711caf2008-06-11 16:44:04 +0000114 self._task_handler._state = RUN
115 self._task_handler.start()
116
117 self._result_handler = threading.Thread(
118 target=Pool._handle_results,
119 args=(self._outqueue, self._quick_get, self._cache)
120 )
Benjamin Petersonfae4c622008-08-18 18:40:08 +0000121 self._result_handler.daemon = True
Benjamin Petersone711caf2008-06-11 16:44:04 +0000122 self._result_handler._state = RUN
123 self._result_handler.start()
124
125 self._terminate = Finalize(
126 self, self._terminate_pool,
127 args=(self._taskqueue, self._inqueue, self._outqueue, self._pool,
128 self._task_handler, self._result_handler, self._cache),
129 exitpriority=15
130 )
131
132 def _setup_queues(self):
133 from .queues import SimpleQueue
134 self._inqueue = SimpleQueue()
135 self._outqueue = SimpleQueue()
136 self._quick_put = self._inqueue._writer.send
137 self._quick_get = self._outqueue._reader.recv
138
139 def apply(self, func, args=(), kwds={}):
140 '''
Georg Brandl92905032008-11-22 08:51:39 +0000141 Equivalent of `func(*args, **kwds)`.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000142 '''
143 assert self._state == RUN
144 return self.apply_async(func, args, kwds).get()
145
146 def map(self, func, iterable, chunksize=None):
147 '''
Georg Brandl92905032008-11-22 08:51:39 +0000148 Apply `func` to each element in `iterable`, collecting the results
149 in a list that is returned.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000150 '''
151 assert self._state == RUN
152 return self.map_async(func, iterable, chunksize).get()
153
154 def imap(self, func, iterable, chunksize=1):
155 '''
Georg Brandl92905032008-11-22 08:51:39 +0000156 Equivalent of `map()` -- can be MUCH slower than `Pool.map()`.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000157 '''
158 assert self._state == RUN
159 if chunksize == 1:
160 result = IMapIterator(self._cache)
161 self._taskqueue.put((((result._job, i, func, (x,), {})
162 for i, x in enumerate(iterable)), result._set_length))
163 return result
164 else:
165 assert chunksize > 1
166 task_batches = Pool._get_tasks(func, iterable, chunksize)
167 result = IMapIterator(self._cache)
168 self._taskqueue.put((((result._job, i, mapstar, (x,), {})
169 for i, x in enumerate(task_batches)), result._set_length))
170 return (item for chunk in result for item in chunk)
171
172 def imap_unordered(self, func, iterable, chunksize=1):
173 '''
Georg Brandl92905032008-11-22 08:51:39 +0000174 Like `imap()` method but ordering of results is arbitrary.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000175 '''
176 assert self._state == RUN
177 if chunksize == 1:
178 result = IMapUnorderedIterator(self._cache)
179 self._taskqueue.put((((result._job, i, func, (x,), {})
180 for i, x in enumerate(iterable)), result._set_length))
181 return result
182 else:
183 assert chunksize > 1
184 task_batches = Pool._get_tasks(func, iterable, chunksize)
185 result = IMapUnorderedIterator(self._cache)
186 self._taskqueue.put((((result._job, i, mapstar, (x,), {})
187 for i, x in enumerate(task_batches)), result._set_length))
188 return (item for chunk in result for item in chunk)
189
190 def apply_async(self, func, args=(), kwds={}, callback=None):
191 '''
Georg Brandl92905032008-11-22 08:51:39 +0000192 Asynchronous version of `apply()` method.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000193 '''
194 assert self._state == RUN
195 result = ApplyResult(self._cache, callback)
196 self._taskqueue.put(([(result._job, None, func, args, kwds)], None))
197 return result
198
199 def map_async(self, func, iterable, chunksize=None, callback=None):
200 '''
Georg Brandl92905032008-11-22 08:51:39 +0000201 Asynchronous version of `map()` method.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000202 '''
203 assert self._state == RUN
204 if not hasattr(iterable, '__len__'):
205 iterable = list(iterable)
206
207 if chunksize is None:
208 chunksize, extra = divmod(len(iterable), len(self._pool) * 4)
209 if extra:
210 chunksize += 1
211
212 task_batches = Pool._get_tasks(func, iterable, chunksize)
213 result = MapResult(self._cache, chunksize, len(iterable), callback)
214 self._taskqueue.put((((result._job, i, mapstar, (x,), {})
215 for i, x in enumerate(task_batches)), None))
216 return result
217
218 @staticmethod
219 def _handle_tasks(taskqueue, put, outqueue, pool):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000220 thread = threading.current_thread()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000221
222 for taskseq, set_length in iter(taskqueue.get, None):
223 i = -1
224 for i, task in enumerate(taskseq):
225 if thread._state:
226 debug('task handler found thread._state != RUN')
227 break
228 try:
229 put(task)
230 except IOError:
231 debug('could not put task on queue')
232 break
233 else:
234 if set_length:
235 debug('doing set_length()')
236 set_length(i+1)
237 continue
238 break
239 else:
240 debug('task handler got sentinel')
241
242
243 try:
244 # tell result handler to finish when cache is empty
245 debug('task handler sending sentinel to result handler')
246 outqueue.put(None)
247
248 # tell workers there is no more work
249 debug('task handler sending sentinel to workers')
250 for p in pool:
251 put(None)
252 except IOError:
253 debug('task handler got IOError when sending sentinels')
254
255 debug('task handler exiting')
256
257 @staticmethod
258 def _handle_results(outqueue, get, cache):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000259 thread = threading.current_thread()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000260
261 while 1:
262 try:
263 task = get()
264 except (IOError, EOFError):
265 debug('result handler got EOFError/IOError -- exiting')
266 return
267
268 if thread._state:
269 assert thread._state == TERMINATE
270 debug('result handler found thread._state=TERMINATE')
271 break
272
273 if task is None:
274 debug('result handler got sentinel')
275 break
276
277 job, i, obj = task
278 try:
279 cache[job]._set(i, obj)
280 except KeyError:
281 pass
282
283 while cache and thread._state != TERMINATE:
284 try:
285 task = get()
286 except (IOError, EOFError):
287 debug('result handler got EOFError/IOError -- exiting')
288 return
289
290 if task is None:
291 debug('result handler ignoring extra sentinel')
292 continue
293 job, i, obj = task
294 try:
295 cache[job]._set(i, obj)
296 except KeyError:
297 pass
298
299 if hasattr(outqueue, '_reader'):
300 debug('ensuring that outqueue is not full')
301 # If we don't make room available in outqueue then
302 # attempts to add the sentinel (None) to outqueue may
303 # block. There is guaranteed to be no more than 2 sentinels.
304 try:
305 for i in range(10):
306 if not outqueue._reader.poll():
307 break
308 get()
309 except (IOError, EOFError):
310 pass
311
312 debug('result handler exiting: len(cache)=%s, thread._state=%s',
313 len(cache), thread._state)
314
315 @staticmethod
316 def _get_tasks(func, it, size):
317 it = iter(it)
318 while 1:
319 x = tuple(itertools.islice(it, size))
320 if not x:
321 return
322 yield (func, x)
323
324 def __reduce__(self):
325 raise NotImplementedError(
326 'pool objects cannot be passed between processes or pickled'
327 )
328
329 def close(self):
330 debug('closing pool')
331 if self._state == RUN:
332 self._state = CLOSE
333 self._taskqueue.put(None)
334
335 def terminate(self):
336 debug('terminating pool')
337 self._state = TERMINATE
338 self._terminate()
339
340 def join(self):
341 debug('joining pool')
342 assert self._state in (CLOSE, TERMINATE)
343 self._task_handler.join()
344 self._result_handler.join()
345 for p in self._pool:
346 p.join()
347
348 @staticmethod
349 def _help_stuff_finish(inqueue, task_handler, size):
350 # task_handler may be blocked trying to put items on inqueue
351 debug('removing tasks from inqueue until task handler finished')
352 inqueue._rlock.acquire()
Benjamin Peterson672b8032008-06-11 19:14:14 +0000353 while task_handler.is_alive() and inqueue._reader.poll():
Benjamin Petersone711caf2008-06-11 16:44:04 +0000354 inqueue._reader.recv()
355 time.sleep(0)
356
357 @classmethod
358 def _terminate_pool(cls, taskqueue, inqueue, outqueue, pool,
359 task_handler, result_handler, cache):
360 # this is guaranteed to only be called once
361 debug('finalizing pool')
362
363 task_handler._state = TERMINATE
364 taskqueue.put(None) # sentinel
365
366 debug('helping task handler/workers to finish')
367 cls._help_stuff_finish(inqueue, task_handler, len(pool))
368
Benjamin Peterson672b8032008-06-11 19:14:14 +0000369 assert result_handler.is_alive() or len(cache) == 0
Benjamin Petersone711caf2008-06-11 16:44:04 +0000370
371 result_handler._state = TERMINATE
372 outqueue.put(None) # sentinel
373
374 if pool and hasattr(pool[0], 'terminate'):
375 debug('terminating workers')
376 for p in pool:
377 p.terminate()
378
379 debug('joining task handler')
380 task_handler.join(1e100)
381
382 debug('joining result handler')
383 result_handler.join(1e100)
384
385 if pool and hasattr(pool[0], 'terminate'):
386 debug('joining pool workers')
387 for p in pool:
388 p.join()
389
390#
391# Class whose instances are returned by `Pool.apply_async()`
392#
393
394class ApplyResult(object):
395
396 def __init__(self, cache, callback):
397 self._cond = threading.Condition(threading.Lock())
398 self._job = next(job_counter)
399 self._cache = cache
400 self._ready = False
401 self._callback = callback
402 cache[self._job] = self
403
404 def ready(self):
405 return self._ready
406
407 def successful(self):
408 assert self._ready
409 return self._success
410
411 def wait(self, timeout=None):
412 self._cond.acquire()
413 try:
414 if not self._ready:
415 self._cond.wait(timeout)
416 finally:
417 self._cond.release()
418
419 def get(self, timeout=None):
420 self.wait(timeout)
421 if not self._ready:
422 raise TimeoutError
423 if self._success:
424 return self._value
425 else:
426 raise self._value
427
428 def _set(self, i, obj):
429 self._success, self._value = obj
430 if self._callback and self._success:
431 self._callback(self._value)
432 self._cond.acquire()
433 try:
434 self._ready = True
435 self._cond.notify()
436 finally:
437 self._cond.release()
438 del self._cache[self._job]
439
440#
441# Class whose instances are returned by `Pool.map_async()`
442#
443
444class MapResult(ApplyResult):
445
446 def __init__(self, cache, chunksize, length, callback):
447 ApplyResult.__init__(self, cache, callback)
448 self._success = True
449 self._value = [None] * length
450 self._chunksize = chunksize
451 if chunksize <= 0:
452 self._number_left = 0
453 self._ready = True
454 else:
455 self._number_left = length//chunksize + bool(length % chunksize)
456
457 def _set(self, i, success_result):
458 success, result = success_result
459 if success:
460 self._value[i*self._chunksize:(i+1)*self._chunksize] = result
461 self._number_left -= 1
462 if self._number_left == 0:
463 if self._callback:
464 self._callback(self._value)
465 del self._cache[self._job]
466 self._cond.acquire()
467 try:
468 self._ready = True
469 self._cond.notify()
470 finally:
471 self._cond.release()
472
473 else:
474 self._success = False
475 self._value = result
476 del self._cache[self._job]
477 self._cond.acquire()
478 try:
479 self._ready = True
480 self._cond.notify()
481 finally:
482 self._cond.release()
483
484#
485# Class whose instances are returned by `Pool.imap()`
486#
487
488class IMapIterator(object):
489
490 def __init__(self, cache):
491 self._cond = threading.Condition(threading.Lock())
492 self._job = next(job_counter)
493 self._cache = cache
494 self._items = collections.deque()
495 self._index = 0
496 self._length = None
497 self._unsorted = {}
498 cache[self._job] = self
499
500 def __iter__(self):
501 return self
502
503 def next(self, timeout=None):
504 self._cond.acquire()
505 try:
506 try:
507 item = self._items.popleft()
508 except IndexError:
509 if self._index == self._length:
510 raise StopIteration
511 self._cond.wait(timeout)
512 try:
513 item = self._items.popleft()
514 except IndexError:
515 if self._index == self._length:
516 raise StopIteration
517 raise TimeoutError
518 finally:
519 self._cond.release()
520
521 success, value = item
522 if success:
523 return value
524 raise value
525
526 __next__ = next # XXX
527
528 def _set(self, i, obj):
529 self._cond.acquire()
530 try:
531 if self._index == i:
532 self._items.append(obj)
533 self._index += 1
534 while self._index in self._unsorted:
535 obj = self._unsorted.pop(self._index)
536 self._items.append(obj)
537 self._index += 1
538 self._cond.notify()
539 else:
540 self._unsorted[i] = obj
541
542 if self._index == self._length:
543 del self._cache[self._job]
544 finally:
545 self._cond.release()
546
547 def _set_length(self, length):
548 self._cond.acquire()
549 try:
550 self._length = length
551 if self._index == self._length:
552 self._cond.notify()
553 del self._cache[self._job]
554 finally:
555 self._cond.release()
556
557#
558# Class whose instances are returned by `Pool.imap_unordered()`
559#
560
561class IMapUnorderedIterator(IMapIterator):
562
563 def _set(self, i, obj):
564 self._cond.acquire()
565 try:
566 self._items.append(obj)
567 self._index += 1
568 self._cond.notify()
569 if self._index == self._length:
570 del self._cache[self._job]
571 finally:
572 self._cond.release()
573
574#
575#
576#
577
578class ThreadPool(Pool):
579
580 from .dummy import Process
581
582 def __init__(self, processes=None, initializer=None, initargs=()):
583 Pool.__init__(self, processes, initializer, initargs)
584
585 def _setup_queues(self):
586 self._inqueue = queue.Queue()
587 self._outqueue = queue.Queue()
588 self._quick_put = self._inqueue.put
589 self._quick_get = self._outqueue.get
590
591 @staticmethod
592 def _help_stuff_finish(inqueue, task_handler, size):
593 # put sentinels at head of inqueue to make workers finish
594 inqueue.not_empty.acquire()
595 try:
596 inqueue.queue.clear()
597 inqueue.queue.extend([None] * size)
Benjamin Peterson672b8032008-06-11 19:14:14 +0000598 inqueue.not_empty.notify_all()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000599 finally:
600 inqueue.not_empty.release()