blob: d3ecc9b84b35a0d3579fd0d74b61fc0ced5c8b24 [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
Alexandre Vassalottie52e3782009-07-17 09:18:18 +0000211 if len(iterable) == 0:
212 chunksize = 0
Benjamin Petersone711caf2008-06-11 16:44:04 +0000213
214 task_batches = Pool._get_tasks(func, iterable, chunksize)
215 result = MapResult(self._cache, chunksize, len(iterable), callback)
216 self._taskqueue.put((((result._job, i, mapstar, (x,), {})
217 for i, x in enumerate(task_batches)), None))
218 return result
219
220 @staticmethod
221 def _handle_tasks(taskqueue, put, outqueue, pool):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000222 thread = threading.current_thread()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000223
224 for taskseq, set_length in iter(taskqueue.get, None):
225 i = -1
226 for i, task in enumerate(taskseq):
227 if thread._state:
228 debug('task handler found thread._state != RUN')
229 break
230 try:
231 put(task)
232 except IOError:
233 debug('could not put task on queue')
234 break
235 else:
236 if set_length:
237 debug('doing set_length()')
238 set_length(i+1)
239 continue
240 break
241 else:
242 debug('task handler got sentinel')
243
244
245 try:
246 # tell result handler to finish when cache is empty
247 debug('task handler sending sentinel to result handler')
248 outqueue.put(None)
249
250 # tell workers there is no more work
251 debug('task handler sending sentinel to workers')
252 for p in pool:
253 put(None)
254 except IOError:
255 debug('task handler got IOError when sending sentinels')
256
257 debug('task handler exiting')
258
259 @staticmethod
260 def _handle_results(outqueue, get, cache):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000261 thread = threading.current_thread()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000262
263 while 1:
264 try:
265 task = get()
266 except (IOError, EOFError):
267 debug('result handler got EOFError/IOError -- exiting')
268 return
269
270 if thread._state:
271 assert thread._state == TERMINATE
272 debug('result handler found thread._state=TERMINATE')
273 break
274
275 if task is None:
276 debug('result handler got sentinel')
277 break
278
279 job, i, obj = task
280 try:
281 cache[job]._set(i, obj)
282 except KeyError:
283 pass
284
285 while cache and thread._state != TERMINATE:
286 try:
287 task = get()
288 except (IOError, EOFError):
289 debug('result handler got EOFError/IOError -- exiting')
290 return
291
292 if task is None:
293 debug('result handler ignoring extra sentinel')
294 continue
295 job, i, obj = task
296 try:
297 cache[job]._set(i, obj)
298 except KeyError:
299 pass
300
301 if hasattr(outqueue, '_reader'):
302 debug('ensuring that outqueue is not full')
303 # If we don't make room available in outqueue then
304 # attempts to add the sentinel (None) to outqueue may
305 # block. There is guaranteed to be no more than 2 sentinels.
306 try:
307 for i in range(10):
308 if not outqueue._reader.poll():
309 break
310 get()
311 except (IOError, EOFError):
312 pass
313
314 debug('result handler exiting: len(cache)=%s, thread._state=%s',
315 len(cache), thread._state)
316
317 @staticmethod
318 def _get_tasks(func, it, size):
319 it = iter(it)
320 while 1:
321 x = tuple(itertools.islice(it, size))
322 if not x:
323 return
324 yield (func, x)
325
326 def __reduce__(self):
327 raise NotImplementedError(
328 'pool objects cannot be passed between processes or pickled'
329 )
330
331 def close(self):
332 debug('closing pool')
333 if self._state == RUN:
334 self._state = CLOSE
335 self._taskqueue.put(None)
336
337 def terminate(self):
338 debug('terminating pool')
339 self._state = TERMINATE
340 self._terminate()
341
342 def join(self):
343 debug('joining pool')
344 assert self._state in (CLOSE, TERMINATE)
345 self._task_handler.join()
346 self._result_handler.join()
347 for p in self._pool:
348 p.join()
349
350 @staticmethod
351 def _help_stuff_finish(inqueue, task_handler, size):
352 # task_handler may be blocked trying to put items on inqueue
353 debug('removing tasks from inqueue until task handler finished')
354 inqueue._rlock.acquire()
Benjamin Peterson672b8032008-06-11 19:14:14 +0000355 while task_handler.is_alive() and inqueue._reader.poll():
Benjamin Petersone711caf2008-06-11 16:44:04 +0000356 inqueue._reader.recv()
357 time.sleep(0)
358
359 @classmethod
360 def _terminate_pool(cls, taskqueue, inqueue, outqueue, pool,
361 task_handler, result_handler, cache):
362 # this is guaranteed to only be called once
363 debug('finalizing pool')
364
365 task_handler._state = TERMINATE
366 taskqueue.put(None) # sentinel
367
368 debug('helping task handler/workers to finish')
369 cls._help_stuff_finish(inqueue, task_handler, len(pool))
370
Benjamin Peterson672b8032008-06-11 19:14:14 +0000371 assert result_handler.is_alive() or len(cache) == 0
Benjamin Petersone711caf2008-06-11 16:44:04 +0000372
373 result_handler._state = TERMINATE
374 outqueue.put(None) # sentinel
375
376 if pool and hasattr(pool[0], 'terminate'):
377 debug('terminating workers')
378 for p in pool:
379 p.terminate()
380
381 debug('joining task handler')
382 task_handler.join(1e100)
383
384 debug('joining result handler')
385 result_handler.join(1e100)
386
387 if pool and hasattr(pool[0], 'terminate'):
388 debug('joining pool workers')
389 for p in pool:
390 p.join()
391
392#
393# Class whose instances are returned by `Pool.apply_async()`
394#
395
396class ApplyResult(object):
397
398 def __init__(self, cache, callback):
399 self._cond = threading.Condition(threading.Lock())
400 self._job = next(job_counter)
401 self._cache = cache
402 self._ready = False
403 self._callback = callback
404 cache[self._job] = self
405
406 def ready(self):
407 return self._ready
408
409 def successful(self):
410 assert self._ready
411 return self._success
412
413 def wait(self, timeout=None):
414 self._cond.acquire()
415 try:
416 if not self._ready:
417 self._cond.wait(timeout)
418 finally:
419 self._cond.release()
420
421 def get(self, timeout=None):
422 self.wait(timeout)
423 if not self._ready:
424 raise TimeoutError
425 if self._success:
426 return self._value
427 else:
428 raise self._value
429
430 def _set(self, i, obj):
431 self._success, self._value = obj
432 if self._callback and self._success:
433 self._callback(self._value)
434 self._cond.acquire()
435 try:
436 self._ready = True
437 self._cond.notify()
438 finally:
439 self._cond.release()
440 del self._cache[self._job]
441
442#
443# Class whose instances are returned by `Pool.map_async()`
444#
445
446class MapResult(ApplyResult):
447
448 def __init__(self, cache, chunksize, length, callback):
449 ApplyResult.__init__(self, cache, callback)
450 self._success = True
451 self._value = [None] * length
452 self._chunksize = chunksize
453 if chunksize <= 0:
454 self._number_left = 0
455 self._ready = True
456 else:
457 self._number_left = length//chunksize + bool(length % chunksize)
458
459 def _set(self, i, success_result):
460 success, result = success_result
461 if success:
462 self._value[i*self._chunksize:(i+1)*self._chunksize] = result
463 self._number_left -= 1
464 if self._number_left == 0:
465 if self._callback:
466 self._callback(self._value)
467 del self._cache[self._job]
468 self._cond.acquire()
469 try:
470 self._ready = True
471 self._cond.notify()
472 finally:
473 self._cond.release()
474
475 else:
476 self._success = False
477 self._value = result
478 del self._cache[self._job]
479 self._cond.acquire()
480 try:
481 self._ready = True
482 self._cond.notify()
483 finally:
484 self._cond.release()
485
486#
487# Class whose instances are returned by `Pool.imap()`
488#
489
490class IMapIterator(object):
491
492 def __init__(self, cache):
493 self._cond = threading.Condition(threading.Lock())
494 self._job = next(job_counter)
495 self._cache = cache
496 self._items = collections.deque()
497 self._index = 0
498 self._length = None
499 self._unsorted = {}
500 cache[self._job] = self
501
502 def __iter__(self):
503 return self
504
505 def next(self, timeout=None):
506 self._cond.acquire()
507 try:
508 try:
509 item = self._items.popleft()
510 except IndexError:
511 if self._index == self._length:
512 raise StopIteration
513 self._cond.wait(timeout)
514 try:
515 item = self._items.popleft()
516 except IndexError:
517 if self._index == self._length:
518 raise StopIteration
519 raise TimeoutError
520 finally:
521 self._cond.release()
522
523 success, value = item
524 if success:
525 return value
526 raise value
527
528 __next__ = next # XXX
529
530 def _set(self, i, obj):
531 self._cond.acquire()
532 try:
533 if self._index == i:
534 self._items.append(obj)
535 self._index += 1
536 while self._index in self._unsorted:
537 obj = self._unsorted.pop(self._index)
538 self._items.append(obj)
539 self._index += 1
540 self._cond.notify()
541 else:
542 self._unsorted[i] = obj
543
544 if self._index == self._length:
545 del self._cache[self._job]
546 finally:
547 self._cond.release()
548
549 def _set_length(self, length):
550 self._cond.acquire()
551 try:
552 self._length = length
553 if self._index == self._length:
554 self._cond.notify()
555 del self._cache[self._job]
556 finally:
557 self._cond.release()
558
559#
560# Class whose instances are returned by `Pool.imap_unordered()`
561#
562
563class IMapUnorderedIterator(IMapIterator):
564
565 def _set(self, i, obj):
566 self._cond.acquire()
567 try:
568 self._items.append(obj)
569 self._index += 1
570 self._cond.notify()
571 if self._index == self._length:
572 del self._cache[self._job]
573 finally:
574 self._cond.release()
575
576#
577#
578#
579
580class ThreadPool(Pool):
581
582 from .dummy import Process
583
584 def __init__(self, processes=None, initializer=None, initargs=()):
585 Pool.__init__(self, processes, initializer, initargs)
586
587 def _setup_queues(self):
588 self._inqueue = queue.Queue()
589 self._outqueue = queue.Queue()
590 self._quick_put = self._inqueue.put
591 self._quick_get = self._outqueue.get
592
593 @staticmethod
594 def _help_stuff_finish(inqueue, task_handler, size):
595 # put sentinels at head of inqueue to make workers finish
596 inqueue.not_empty.acquire()
597 try:
598 inqueue.queue.clear()
599 inqueue.queue.extend([None] * size)
Benjamin Peterson672b8032008-06-11 19:14:14 +0000600 inqueue.not_empty.notify_all()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000601 finally:
602 inqueue.not_empty.release()