ยปCore Development>Code coverage>Lib/multiprocessing/pool.py

Python code coverage for Lib/multiprocessing/pool.py

#countcontent
1n/a#
2n/a# Module providing the `Pool` class for managing a process pool
3n/a#
4n/a# multiprocessing/pool.py
5n/a#
6n/a# Copyright (c) 2006-2008, R Oudkerk
7n/a# Licensed to PSF under a Contributor Agreement.
8n/a#
9n/a
10n/a__all__ = ['Pool', 'ThreadPool']
11n/a
12n/a#
13n/a# Imports
14n/a#
15n/a
16n/aimport threading
17n/aimport queue
18n/aimport itertools
19n/aimport collections
20n/aimport os
21n/aimport time
22n/aimport traceback
23n/a
24n/a# If threading is available then ThreadPool should be provided. Therefore
25n/a# we avoid top-level imports which are liable to fail on some systems.
26n/afrom . import util
27n/afrom . import get_context, TimeoutError
28n/a
29n/a#
30n/a# Constants representing the state of a pool
31n/a#
32n/a
33n/aRUN = 0
34n/aCLOSE = 1
35n/aTERMINATE = 2
36n/a
37n/a#
38n/a# Miscellaneous
39n/a#
40n/a
41n/ajob_counter = itertools.count()
42n/a
43n/adef mapstar(args):
44n/a return list(map(*args))
45n/a
46n/adef starmapstar(args):
47n/a return list(itertools.starmap(args[0], args[1]))
48n/a
49n/a#
50n/a# Hack to embed stringification of remote traceback in local traceback
51n/a#
52n/a
53n/aclass RemoteTraceback(Exception):
54n/a def __init__(self, tb):
55n/a self.tb = tb
56n/a def __str__(self):
57n/a return self.tb
58n/a
59n/aclass ExceptionWithTraceback:
60n/a def __init__(self, exc, tb):
61n/a tb = traceback.format_exception(type(exc), exc, tb)
62n/a tb = ''.join(tb)
63n/a self.exc = exc
64n/a self.tb = '\n"""\n%s"""' % tb
65n/a def __reduce__(self):
66n/a return rebuild_exc, (self.exc, self.tb)
67n/a
68n/adef rebuild_exc(exc, tb):
69n/a exc.__cause__ = RemoteTraceback(tb)
70n/a return exc
71n/a
72n/a#
73n/a# Code run by worker processes
74n/a#
75n/a
76n/aclass MaybeEncodingError(Exception):
77n/a """Wraps possible unpickleable errors, so they can be
78n/a safely sent through the socket."""
79n/a
80n/a def __init__(self, exc, value):
81n/a self.exc = repr(exc)
82n/a self.value = repr(value)
83n/a super(MaybeEncodingError, self).__init__(self.exc, self.value)
84n/a
85n/a def __str__(self):
86n/a return "Error sending result: '%s'. Reason: '%s'" % (self.value,
87n/a self.exc)
88n/a
89n/a def __repr__(self):
90n/a return "<%s: %s>" % (self.__class__.__name__, self)
91n/a
92n/a
93n/adef worker(inqueue, outqueue, initializer=None, initargs=(), maxtasks=None,
94n/a wrap_exception=False):
95n/a assert maxtasks is None or (type(maxtasks) == int and maxtasks > 0)
96n/a put = outqueue.put
97n/a get = inqueue.get
98n/a if hasattr(inqueue, '_writer'):
99n/a inqueue._writer.close()
100n/a outqueue._reader.close()
101n/a
102n/a if initializer is not None:
103n/a initializer(*initargs)
104n/a
105n/a completed = 0
106n/a while maxtasks is None or (maxtasks and completed < maxtasks):
107n/a try:
108n/a task = get()
109n/a except (EOFError, OSError):
110n/a util.debug('worker got EOFError or OSError -- exiting')
111n/a break
112n/a
113n/a if task is None:
114n/a util.debug('worker got sentinel -- exiting')
115n/a break
116n/a
117n/a job, i, func, args, kwds = task
118n/a try:
119n/a result = (True, func(*args, **kwds))
120n/a except Exception as e:
121n/a if wrap_exception:
122n/a e = ExceptionWithTraceback(e, e.__traceback__)
123n/a result = (False, e)
124n/a try:
125n/a put((job, i, result))
126n/a except Exception as e:
127n/a wrapped = MaybeEncodingError(e, result[1])
128n/a util.debug("Possible encoding error while sending result: %s" % (
129n/a wrapped))
130n/a put((job, i, (False, wrapped)))
131n/a completed += 1
132n/a util.debug('worker exiting after %d tasks' % completed)
133n/a
134n/a#
135n/a# Class representing a process pool
136n/a#
137n/a
138n/aclass Pool(object):
139n/a '''
140n/a Class which supports an async version of applying functions to arguments.
141n/a '''
142n/a _wrap_exception = True
143n/a
144n/a def Process(self, *args, **kwds):
145n/a return self._ctx.Process(*args, **kwds)
146n/a
147n/a def __init__(self, processes=None, initializer=None, initargs=(),
148n/a maxtasksperchild=None, context=None):
149n/a self._ctx = context or get_context()
150n/a self._setup_queues()
151n/a self._taskqueue = queue.Queue()
152n/a self._cache = {}
153n/a self._state = RUN
154n/a self._maxtasksperchild = maxtasksperchild
155n/a self._initializer = initializer
156n/a self._initargs = initargs
157n/a
158n/a if processes is None:
159n/a processes = os.cpu_count() or 1
160n/a if processes < 1:
161n/a raise ValueError("Number of processes must be at least 1")
162n/a
163n/a if initializer is not None and not callable(initializer):
164n/a raise TypeError('initializer must be a callable')
165n/a
166n/a self._processes = processes
167n/a self._pool = []
168n/a self._repopulate_pool()
169n/a
170n/a self._worker_handler = threading.Thread(
171n/a target=Pool._handle_workers,
172n/a args=(self, )
173n/a )
174n/a self._worker_handler.daemon = True
175n/a self._worker_handler._state = RUN
176n/a self._worker_handler.start()
177n/a
178n/a
179n/a self._task_handler = threading.Thread(
180n/a target=Pool._handle_tasks,
181n/a args=(self._taskqueue, self._quick_put, self._outqueue,
182n/a self._pool, self._cache)
183n/a )
184n/a self._task_handler.daemon = True
185n/a self._task_handler._state = RUN
186n/a self._task_handler.start()
187n/a
188n/a self._result_handler = threading.Thread(
189n/a target=Pool._handle_results,
190n/a args=(self._outqueue, self._quick_get, self._cache)
191n/a )
192n/a self._result_handler.daemon = True
193n/a self._result_handler._state = RUN
194n/a self._result_handler.start()
195n/a
196n/a self._terminate = util.Finalize(
197n/a self, self._terminate_pool,
198n/a args=(self._taskqueue, self._inqueue, self._outqueue, self._pool,
199n/a self._worker_handler, self._task_handler,
200n/a self._result_handler, self._cache),
201n/a exitpriority=15
202n/a )
203n/a
204n/a def _join_exited_workers(self):
205n/a """Cleanup after any worker processes which have exited due to reaching
206n/a their specified lifetime. Returns True if any workers were cleaned up.
207n/a """
208n/a cleaned = False
209n/a for i in reversed(range(len(self._pool))):
210n/a worker = self._pool[i]
211n/a if worker.exitcode is not None:
212n/a # worker exited
213n/a util.debug('cleaning up worker %d' % i)
214n/a worker.join()
215n/a cleaned = True
216n/a del self._pool[i]
217n/a return cleaned
218n/a
219n/a def _repopulate_pool(self):
220n/a """Bring the number of pool processes up to the specified number,
221n/a for use after reaping workers which have exited.
222n/a """
223n/a for i in range(self._processes - len(self._pool)):
224n/a w = self.Process(target=worker,
225n/a args=(self._inqueue, self._outqueue,
226n/a self._initializer,
227n/a self._initargs, self._maxtasksperchild,
228n/a self._wrap_exception)
229n/a )
230n/a self._pool.append(w)
231n/a w.name = w.name.replace('Process', 'PoolWorker')
232n/a w.daemon = True
233n/a w.start()
234n/a util.debug('added worker')
235n/a
236n/a def _maintain_pool(self):
237n/a """Clean up any exited workers and start replacements for them.
238n/a """
239n/a if self._join_exited_workers():
240n/a self._repopulate_pool()
241n/a
242n/a def _setup_queues(self):
243n/a self._inqueue = self._ctx.SimpleQueue()
244n/a self._outqueue = self._ctx.SimpleQueue()
245n/a self._quick_put = self._inqueue._writer.send
246n/a self._quick_get = self._outqueue._reader.recv
247n/a
248n/a def apply(self, func, args=(), kwds={}):
249n/a '''
250n/a Equivalent of `func(*args, **kwds)`.
251n/a '''
252n/a assert self._state == RUN
253n/a return self.apply_async(func, args, kwds).get()
254n/a
255n/a def map(self, func, iterable, chunksize=None):
256n/a '''
257n/a Apply `func` to each element in `iterable`, collecting the results
258n/a in a list that is returned.
259n/a '''
260n/a return self._map_async(func, iterable, mapstar, chunksize).get()
261n/a
262n/a def starmap(self, func, iterable, chunksize=None):
263n/a '''
264n/a Like `map()` method but the elements of the `iterable` are expected to
265n/a be iterables as well and will be unpacked as arguments. Hence
266n/a `func` and (a, b) becomes func(a, b).
267n/a '''
268n/a return self._map_async(func, iterable, starmapstar, chunksize).get()
269n/a
270n/a def starmap_async(self, func, iterable, chunksize=None, callback=None,
271n/a error_callback=None):
272n/a '''
273n/a Asynchronous version of `starmap()` method.
274n/a '''
275n/a return self._map_async(func, iterable, starmapstar, chunksize,
276n/a callback, error_callback)
277n/a
278n/a def imap(self, func, iterable, chunksize=1):
279n/a '''
280n/a Equivalent of `map()` -- can be MUCH slower than `Pool.map()`.
281n/a '''
282n/a if self._state != RUN:
283n/a raise ValueError("Pool not running")
284n/a if chunksize == 1:
285n/a result = IMapIterator(self._cache)
286n/a self._taskqueue.put((((result._job, i, func, (x,), {})
287n/a for i, x in enumerate(iterable)), result._set_length))
288n/a return result
289n/a else:
290n/a assert chunksize > 1
291n/a task_batches = Pool._get_tasks(func, iterable, chunksize)
292n/a result = IMapIterator(self._cache)
293n/a self._taskqueue.put((((result._job, i, mapstar, (x,), {})
294n/a for i, x in enumerate(task_batches)), result._set_length))
295n/a return (item for chunk in result for item in chunk)
296n/a
297n/a def imap_unordered(self, func, iterable, chunksize=1):
298n/a '''
299n/a Like `imap()` method but ordering of results is arbitrary.
300n/a '''
301n/a if self._state != RUN:
302n/a raise ValueError("Pool not running")
303n/a if chunksize == 1:
304n/a result = IMapUnorderedIterator(self._cache)
305n/a self._taskqueue.put((((result._job, i, func, (x,), {})
306n/a for i, x in enumerate(iterable)), result._set_length))
307n/a return result
308n/a else:
309n/a assert chunksize > 1
310n/a task_batches = Pool._get_tasks(func, iterable, chunksize)
311n/a result = IMapUnorderedIterator(self._cache)
312n/a self._taskqueue.put((((result._job, i, mapstar, (x,), {})
313n/a for i, x in enumerate(task_batches)), result._set_length))
314n/a return (item for chunk in result for item in chunk)
315n/a
316n/a def apply_async(self, func, args=(), kwds={}, callback=None,
317n/a error_callback=None):
318n/a '''
319n/a Asynchronous version of `apply()` method.
320n/a '''
321n/a if self._state != RUN:
322n/a raise ValueError("Pool not running")
323n/a result = ApplyResult(self._cache, callback, error_callback)
324n/a self._taskqueue.put(([(result._job, None, func, args, kwds)], None))
325n/a return result
326n/a
327n/a def map_async(self, func, iterable, chunksize=None, callback=None,
328n/a error_callback=None):
329n/a '''
330n/a Asynchronous version of `map()` method.
331n/a '''
332n/a return self._map_async(func, iterable, mapstar, chunksize, callback,
333n/a error_callback)
334n/a
335n/a def _map_async(self, func, iterable, mapper, chunksize=None, callback=None,
336n/a error_callback=None):
337n/a '''
338n/a Helper function to implement map, starmap and their async counterparts.
339n/a '''
340n/a if self._state != RUN:
341n/a raise ValueError("Pool not running")
342n/a if not hasattr(iterable, '__len__'):
343n/a iterable = list(iterable)
344n/a
345n/a if chunksize is None:
346n/a chunksize, extra = divmod(len(iterable), len(self._pool) * 4)
347n/a if extra:
348n/a chunksize += 1
349n/a if len(iterable) == 0:
350n/a chunksize = 0
351n/a
352n/a task_batches = Pool._get_tasks(func, iterable, chunksize)
353n/a result = MapResult(self._cache, chunksize, len(iterable), callback,
354n/a error_callback=error_callback)
355n/a self._taskqueue.put((((result._job, i, mapper, (x,), {})
356n/a for i, x in enumerate(task_batches)), None))
357n/a return result
358n/a
359n/a @staticmethod
360n/a def _handle_workers(pool):
361n/a thread = threading.current_thread()
362n/a
363n/a # Keep maintaining workers until the cache gets drained, unless the pool
364n/a # is terminated.
365n/a while thread._state == RUN or (pool._cache and thread._state != TERMINATE):
366n/a pool._maintain_pool()
367n/a time.sleep(0.1)
368n/a # send sentinel to stop workers
369n/a pool._taskqueue.put(None)
370n/a util.debug('worker handler exiting')
371n/a
372n/a @staticmethod
373n/a def _handle_tasks(taskqueue, put, outqueue, pool, cache):
374n/a thread = threading.current_thread()
375n/a
376n/a for taskseq, set_length in iter(taskqueue.get, None):
377n/a task = None
378n/a i = -1
379n/a try:
380n/a for i, task in enumerate(taskseq):
381n/a if thread._state:
382n/a util.debug('task handler found thread._state != RUN')
383n/a break
384n/a try:
385n/a put(task)
386n/a except Exception as e:
387n/a job, ind = task[:2]
388n/a try:
389n/a cache[job]._set(ind, (False, e))
390n/a except KeyError:
391n/a pass
392n/a else:
393n/a if set_length:
394n/a util.debug('doing set_length()')
395n/a set_length(i+1)
396n/a continue
397n/a break
398n/a except Exception as ex:
399n/a job, ind = task[:2] if task else (0, 0)
400n/a if job in cache:
401n/a cache[job]._set(ind + 1, (False, ex))
402n/a if set_length:
403n/a util.debug('doing set_length()')
404n/a set_length(i+1)
405n/a else:
406n/a util.debug('task handler got sentinel')
407n/a
408n/a
409n/a try:
410n/a # tell result handler to finish when cache is empty
411n/a util.debug('task handler sending sentinel to result handler')
412n/a outqueue.put(None)
413n/a
414n/a # tell workers there is no more work
415n/a util.debug('task handler sending sentinel to workers')
416n/a for p in pool:
417n/a put(None)
418n/a except OSError:
419n/a util.debug('task handler got OSError when sending sentinels')
420n/a
421n/a util.debug('task handler exiting')
422n/a
423n/a @staticmethod
424n/a def _handle_results(outqueue, get, cache):
425n/a thread = threading.current_thread()
426n/a
427n/a while 1:
428n/a try:
429n/a task = get()
430n/a except (OSError, EOFError):
431n/a util.debug('result handler got EOFError/OSError -- exiting')
432n/a return
433n/a
434n/a if thread._state:
435n/a assert thread._state == TERMINATE
436n/a util.debug('result handler found thread._state=TERMINATE')
437n/a break
438n/a
439n/a if task is None:
440n/a util.debug('result handler got sentinel')
441n/a break
442n/a
443n/a job, i, obj = task
444n/a try:
445n/a cache[job]._set(i, obj)
446n/a except KeyError:
447n/a pass
448n/a
449n/a while cache and thread._state != TERMINATE:
450n/a try:
451n/a task = get()
452n/a except (OSError, EOFError):
453n/a util.debug('result handler got EOFError/OSError -- exiting')
454n/a return
455n/a
456n/a if task is None:
457n/a util.debug('result handler ignoring extra sentinel')
458n/a continue
459n/a job, i, obj = task
460n/a try:
461n/a cache[job]._set(i, obj)
462n/a except KeyError:
463n/a pass
464n/a
465n/a if hasattr(outqueue, '_reader'):
466n/a util.debug('ensuring that outqueue is not full')
467n/a # If we don't make room available in outqueue then
468n/a # attempts to add the sentinel (None) to outqueue may
469n/a # block. There is guaranteed to be no more than 2 sentinels.
470n/a try:
471n/a for i in range(10):
472n/a if not outqueue._reader.poll():
473n/a break
474n/a get()
475n/a except (OSError, EOFError):
476n/a pass
477n/a
478n/a util.debug('result handler exiting: len(cache)=%s, thread._state=%s',
479n/a len(cache), thread._state)
480n/a
481n/a @staticmethod
482n/a def _get_tasks(func, it, size):
483n/a it = iter(it)
484n/a while 1:
485n/a x = tuple(itertools.islice(it, size))
486n/a if not x:
487n/a return
488n/a yield (func, x)
489n/a
490n/a def __reduce__(self):
491n/a raise NotImplementedError(
492n/a 'pool objects cannot be passed between processes or pickled'
493n/a )
494n/a
495n/a def close(self):
496n/a util.debug('closing pool')
497n/a if self._state == RUN:
498n/a self._state = CLOSE
499n/a self._worker_handler._state = CLOSE
500n/a
501n/a def terminate(self):
502n/a util.debug('terminating pool')
503n/a self._state = TERMINATE
504n/a self._worker_handler._state = TERMINATE
505n/a self._terminate()
506n/a
507n/a def join(self):
508n/a util.debug('joining pool')
509n/a assert self._state in (CLOSE, TERMINATE)
510n/a self._worker_handler.join()
511n/a self._task_handler.join()
512n/a self._result_handler.join()
513n/a for p in self._pool:
514n/a p.join()
515n/a
516n/a @staticmethod
517n/a def _help_stuff_finish(inqueue, task_handler, size):
518n/a # task_handler may be blocked trying to put items on inqueue
519n/a util.debug('removing tasks from inqueue until task handler finished')
520n/a inqueue._rlock.acquire()
521n/a while task_handler.is_alive() and inqueue._reader.poll():
522n/a inqueue._reader.recv()
523n/a time.sleep(0)
524n/a
525n/a @classmethod
526n/a def _terminate_pool(cls, taskqueue, inqueue, outqueue, pool,
527n/a worker_handler, task_handler, result_handler, cache):
528n/a # this is guaranteed to only be called once
529n/a util.debug('finalizing pool')
530n/a
531n/a worker_handler._state = TERMINATE
532n/a task_handler._state = TERMINATE
533n/a
534n/a util.debug('helping task handler/workers to finish')
535n/a cls._help_stuff_finish(inqueue, task_handler, len(pool))
536n/a
537n/a assert result_handler.is_alive() or len(cache) == 0
538n/a
539n/a result_handler._state = TERMINATE
540n/a outqueue.put(None) # sentinel
541n/a
542n/a # We must wait for the worker handler to exit before terminating
543n/a # workers because we don't want workers to be restarted behind our back.
544n/a util.debug('joining worker handler')
545n/a if threading.current_thread() is not worker_handler:
546n/a worker_handler.join()
547n/a
548n/a # Terminate workers which haven't already finished.
549n/a if pool and hasattr(pool[0], 'terminate'):
550n/a util.debug('terminating workers')
551n/a for p in pool:
552n/a if p.exitcode is None:
553n/a p.terminate()
554n/a
555n/a util.debug('joining task handler')
556n/a if threading.current_thread() is not task_handler:
557n/a task_handler.join()
558n/a
559n/a util.debug('joining result handler')
560n/a if threading.current_thread() is not result_handler:
561n/a result_handler.join()
562n/a
563n/a if pool and hasattr(pool[0], 'terminate'):
564n/a util.debug('joining pool workers')
565n/a for p in pool:
566n/a if p.is_alive():
567n/a # worker has not yet exited
568n/a util.debug('cleaning up worker %d' % p.pid)
569n/a p.join()
570n/a
571n/a def __enter__(self):
572n/a return self
573n/a
574n/a def __exit__(self, exc_type, exc_val, exc_tb):
575n/a self.terminate()
576n/a
577n/a#
578n/a# Class whose instances are returned by `Pool.apply_async()`
579n/a#
580n/a
581n/aclass ApplyResult(object):
582n/a
583n/a def __init__(self, cache, callback, error_callback):
584n/a self._event = threading.Event()
585n/a self._job = next(job_counter)
586n/a self._cache = cache
587n/a self._callback = callback
588n/a self._error_callback = error_callback
589n/a cache[self._job] = self
590n/a
591n/a def ready(self):
592n/a return self._event.is_set()
593n/a
594n/a def successful(self):
595n/a assert self.ready()
596n/a return self._success
597n/a
598n/a def wait(self, timeout=None):
599n/a self._event.wait(timeout)
600n/a
601n/a def get(self, timeout=None):
602n/a self.wait(timeout)
603n/a if not self.ready():
604n/a raise TimeoutError
605n/a if self._success:
606n/a return self._value
607n/a else:
608n/a raise self._value
609n/a
610n/a def _set(self, i, obj):
611n/a self._success, self._value = obj
612n/a if self._callback and self._success:
613n/a self._callback(self._value)
614n/a if self._error_callback and not self._success:
615n/a self._error_callback(self._value)
616n/a self._event.set()
617n/a del self._cache[self._job]
618n/a
619n/aAsyncResult = ApplyResult # create alias -- see #17805
620n/a
621n/a#
622n/a# Class whose instances are returned by `Pool.map_async()`
623n/a#
624n/a
625n/aclass MapResult(ApplyResult):
626n/a
627n/a def __init__(self, cache, chunksize, length, callback, error_callback):
628n/a ApplyResult.__init__(self, cache, callback,
629n/a error_callback=error_callback)
630n/a self._success = True
631n/a self._value = [None] * length
632n/a self._chunksize = chunksize
633n/a if chunksize <= 0:
634n/a self._number_left = 0
635n/a self._event.set()
636n/a del cache[self._job]
637n/a else:
638n/a self._number_left = length//chunksize + bool(length % chunksize)
639n/a
640n/a def _set(self, i, success_result):
641n/a self._number_left -= 1
642n/a success, result = success_result
643n/a if success and self._success:
644n/a self._value[i*self._chunksize:(i+1)*self._chunksize] = result
645n/a if self._number_left == 0:
646n/a if self._callback:
647n/a self._callback(self._value)
648n/a del self._cache[self._job]
649n/a self._event.set()
650n/a else:
651n/a if not success and self._success:
652n/a # only store first exception
653n/a self._success = False
654n/a self._value = result
655n/a if self._number_left == 0:
656n/a # only consider the result ready once all jobs are done
657n/a if self._error_callback:
658n/a self._error_callback(self._value)
659n/a del self._cache[self._job]
660n/a self._event.set()
661n/a
662n/a#
663n/a# Class whose instances are returned by `Pool.imap()`
664n/a#
665n/a
666n/aclass IMapIterator(object):
667n/a
668n/a def __init__(self, cache):
669n/a self._cond = threading.Condition(threading.Lock())
670n/a self._job = next(job_counter)
671n/a self._cache = cache
672n/a self._items = collections.deque()
673n/a self._index = 0
674n/a self._length = None
675n/a self._unsorted = {}
676n/a cache[self._job] = self
677n/a
678n/a def __iter__(self):
679n/a return self
680n/a
681n/a def next(self, timeout=None):
682n/a with self._cond:
683n/a try:
684n/a item = self._items.popleft()
685n/a except IndexError:
686n/a if self._index == self._length:
687n/a raise StopIteration
688n/a self._cond.wait(timeout)
689n/a try:
690n/a item = self._items.popleft()
691n/a except IndexError:
692n/a if self._index == self._length:
693n/a raise StopIteration
694n/a raise TimeoutError
695n/a
696n/a success, value = item
697n/a if success:
698n/a return value
699n/a raise value
700n/a
701n/a __next__ = next # XXX
702n/a
703n/a def _set(self, i, obj):
704n/a with self._cond:
705n/a if self._index == i:
706n/a self._items.append(obj)
707n/a self._index += 1
708n/a while self._index in self._unsorted:
709n/a obj = self._unsorted.pop(self._index)
710n/a self._items.append(obj)
711n/a self._index += 1
712n/a self._cond.notify()
713n/a else:
714n/a self._unsorted[i] = obj
715n/a
716n/a if self._index == self._length:
717n/a del self._cache[self._job]
718n/a
719n/a def _set_length(self, length):
720n/a with self._cond:
721n/a self._length = length
722n/a if self._index == self._length:
723n/a self._cond.notify()
724n/a del self._cache[self._job]
725n/a
726n/a#
727n/a# Class whose instances are returned by `Pool.imap_unordered()`
728n/a#
729n/a
730n/aclass IMapUnorderedIterator(IMapIterator):
731n/a
732n/a def _set(self, i, obj):
733n/a with self._cond:
734n/a self._items.append(obj)
735n/a self._index += 1
736n/a self._cond.notify()
737n/a if self._index == self._length:
738n/a del self._cache[self._job]
739n/a
740n/a#
741n/a#
742n/a#
743n/a
744n/aclass ThreadPool(Pool):
745n/a _wrap_exception = False
746n/a
747n/a @staticmethod
748n/a def Process(*args, **kwds):
749n/a from .dummy import Process
750n/a return Process(*args, **kwds)
751n/a
752n/a def __init__(self, processes=None, initializer=None, initargs=()):
753n/a Pool.__init__(self, processes, initializer, initargs)
754n/a
755n/a def _setup_queues(self):
756n/a self._inqueue = queue.Queue()
757n/a self._outqueue = queue.Queue()
758n/a self._quick_put = self._inqueue.put
759n/a self._quick_get = self._outqueue.get
760n/a
761n/a @staticmethod
762n/a def _help_stuff_finish(inqueue, task_handler, size):
763n/a # put sentinels at head of inqueue to make workers finish
764n/a with inqueue.not_empty:
765n/a inqueue.queue.clear()
766n/a inqueue.queue.extend([None] * size)
767n/a inqueue.not_empty.notify_all()