process.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699
  1. # Copyright 2009 Brian Quinlan. All Rights Reserved.
  2. # Licensed to PSF under a Contributor Agreement.
  3. """Implements ProcessPoolExecutor.
  4. The follow diagram and text describe the data-flow through the system:
  5. |======================= In-process =====================|== Out-of-process ==|
  6. +----------+ +----------+ +--------+ +-----------+ +---------+
  7. | | => | Work Ids | | | | Call Q | | Process |
  8. | | +----------+ | | +-----------+ | Pool |
  9. | | | ... | | | | ... | +---------+
  10. | | | 6 | => | | => | 5, call() | => | |
  11. | | | 7 | | | | ... | | |
  12. | Process | | ... | | Local | +-----------+ | Process |
  13. | Pool | +----------+ | Worker | | #1..n |
  14. | Executor | | Thread | | |
  15. | | +----------- + | | +-----------+ | |
  16. | | <=> | Work Items | <=> | | <= | Result Q | <= | |
  17. | | +------------+ | | +-----------+ | |
  18. | | | 6: call() | | | | ... | | |
  19. | | | future | | | | 4, result | | |
  20. | | | ... | | | | 3, except | | |
  21. +----------+ +------------+ +--------+ +-----------+ +---------+
  22. Executor.submit() called:
  23. - creates a uniquely numbered _WorkItem and adds it to the "Work Items" dict
  24. - adds the id of the _WorkItem to the "Work Ids" queue
  25. Local worker thread:
  26. - reads work ids from the "Work Ids" queue and looks up the corresponding
  27. WorkItem from the "Work Items" dict: if the work item has been cancelled then
  28. it is simply removed from the dict, otherwise it is repackaged as a
  29. _CallItem and put in the "Call Q". New _CallItems are put in the "Call Q"
  30. until "Call Q" is full. NOTE: the size of the "Call Q" is kept small because
  31. calls placed in the "Call Q" can no longer be cancelled with Future.cancel().
  32. - reads _ResultItems from "Result Q", updates the future stored in the
  33. "Work Items" dict and deletes the dict entry
  34. Process #1..n:
  35. - reads _CallItems from "Call Q", executes the calls, and puts the resulting
  36. _ResultItems in "Result Q"
  37. """
  38. __author__ = 'Brian Quinlan (brian@sweetapp.com)'
  39. import atexit
  40. import os
  41. from concurrent.futures import _base
  42. import queue
  43. from queue import Full
  44. import multiprocessing as mp
  45. from multiprocessing.connection import wait
  46. from multiprocessing.queues import Queue
  47. import threading
  48. import weakref
  49. from functools import partial
  50. import itertools
  51. import sys
  52. import traceback
  53. # Workers are created as daemon threads and processes. This is done to allow the
  54. # interpreter to exit when there are still idle processes in a
  55. # ProcessPoolExecutor's process pool (i.e. shutdown() was not called). However,
  56. # allowing workers to die with the interpreter has two undesirable properties:
  57. # - The workers would still be running during interpreter shutdown,
  58. # meaning that they would fail in unpredictable ways.
  59. # - The workers could be killed while evaluating a work item, which could
  60. # be bad if the callable being evaluated has external side-effects e.g.
  61. # writing to a file.
  62. #
  63. # To work around this problem, an exit handler is installed which tells the
  64. # workers to exit when their work queues are empty and then waits until the
  65. # threads/processes finish.
  66. _threads_wakeups = weakref.WeakKeyDictionary()
  67. _global_shutdown = False
  68. class _ThreadWakeup:
  69. def __init__(self):
  70. self._reader, self._writer = mp.Pipe(duplex=False)
  71. def close(self):
  72. self._writer.close()
  73. self._reader.close()
  74. def wakeup(self):
  75. self._writer.send_bytes(b"")
  76. def clear(self):
  77. while self._reader.poll():
  78. self._reader.recv_bytes()
  79. def _python_exit():
  80. global _global_shutdown
  81. _global_shutdown = True
  82. items = list(_threads_wakeups.items())
  83. for _, thread_wakeup in items:
  84. thread_wakeup.wakeup()
  85. for t, _ in items:
  86. t.join()
  87. # Controls how many more calls than processes will be queued in the call queue.
  88. # A smaller number will mean that processes spend more time idle waiting for
  89. # work while a larger number will make Future.cancel() succeed less frequently
  90. # (Futures in the call queue cannot be cancelled).
  91. EXTRA_QUEUED_CALLS = 1
  92. # On Windows, WaitForMultipleObjects is used to wait for processes to finish.
  93. # It can wait on, at most, 63 objects. There is an overhead of two objects:
  94. # - the result queue reader
  95. # - the thread wakeup reader
  96. _MAX_WINDOWS_WORKERS = 63 - 2
  97. # Hack to embed stringification of remote traceback in local traceback
  98. class _RemoteTraceback(Exception):
  99. def __init__(self, tb):
  100. self.tb = tb
  101. def __str__(self):
  102. return self.tb
  103. class _ExceptionWithTraceback:
  104. def __init__(self, exc, tb):
  105. tb = traceback.format_exception(type(exc), exc, tb)
  106. tb = ''.join(tb)
  107. self.exc = exc
  108. self.tb = '\n"""\n%s"""' % tb
  109. def __reduce__(self):
  110. return _rebuild_exc, (self.exc, self.tb)
  111. def _rebuild_exc(exc, tb):
  112. exc.__cause__ = _RemoteTraceback(tb)
  113. return exc
  114. class _WorkItem(object):
  115. def __init__(self, future, fn, args, kwargs):
  116. self.future = future
  117. self.fn = fn
  118. self.args = args
  119. self.kwargs = kwargs
  120. class _ResultItem(object):
  121. def __init__(self, work_id, exception=None, result=None):
  122. self.work_id = work_id
  123. self.exception = exception
  124. self.result = result
  125. class _CallItem(object):
  126. def __init__(self, work_id, fn, args, kwargs):
  127. self.work_id = work_id
  128. self.fn = fn
  129. self.args = args
  130. self.kwargs = kwargs
  131. class _SafeQueue(Queue):
  132. """Safe Queue set exception to the future object linked to a job"""
  133. def __init__(self, max_size=0, *, ctx, pending_work_items):
  134. self.pending_work_items = pending_work_items
  135. super().__init__(max_size, ctx=ctx)
  136. def _on_queue_feeder_error(self, e, obj):
  137. if isinstance(obj, _CallItem):
  138. tb = traceback.format_exception(type(e), e, e.__traceback__)
  139. e.__cause__ = _RemoteTraceback('\n"""\n{}"""'.format(''.join(tb)))
  140. work_item = self.pending_work_items.pop(obj.work_id, None)
  141. # work_item can be None if another process terminated. In this case,
  142. # the queue_manager_thread fails all work_items with BrokenProcessPool
  143. if work_item is not None:
  144. work_item.future.set_exception(e)
  145. else:
  146. super()._on_queue_feeder_error(e, obj)
  147. def _get_chunks(*iterables, chunksize):
  148. """ Iterates over zip()ed iterables in chunks. """
  149. it = zip(*iterables)
  150. while True:
  151. chunk = tuple(itertools.islice(it, chunksize))
  152. if not chunk:
  153. return
  154. yield chunk
  155. def _process_chunk(fn, chunk):
  156. """ Processes a chunk of an iterable passed to map.
  157. Runs the function passed to map() on a chunk of the
  158. iterable passed to map.
  159. This function is run in a separate process.
  160. """
  161. return [fn(*args) for args in chunk]
  162. def _sendback_result(result_queue, work_id, result=None, exception=None):
  163. """Safely send back the given result or exception"""
  164. try:
  165. result_queue.put(_ResultItem(work_id, result=result,
  166. exception=exception))
  167. except BaseException as e:
  168. exc = _ExceptionWithTraceback(e, e.__traceback__)
  169. result_queue.put(_ResultItem(work_id, exception=exc))
  170. def _process_worker(call_queue, result_queue, initializer, initargs):
  171. """Evaluates calls from call_queue and places the results in result_queue.
  172. This worker is run in a separate process.
  173. Args:
  174. call_queue: A ctx.Queue of _CallItems that will be read and
  175. evaluated by the worker.
  176. result_queue: A ctx.Queue of _ResultItems that will written
  177. to by the worker.
  178. initializer: A callable initializer, or None
  179. initargs: A tuple of args for the initializer
  180. """
  181. if initializer is not None:
  182. try:
  183. initializer(*initargs)
  184. except BaseException:
  185. _base.LOGGER.critical('Exception in initializer:', exc_info=True)
  186. # The parent will notice that the process stopped and
  187. # mark the pool broken
  188. return
  189. while True:
  190. call_item = call_queue.get(block=True)
  191. if call_item is None:
  192. # Wake up queue management thread
  193. result_queue.put(os.getpid())
  194. return
  195. try:
  196. r = call_item.fn(*call_item.args, **call_item.kwargs)
  197. except BaseException as e:
  198. exc = _ExceptionWithTraceback(e, e.__traceback__)
  199. _sendback_result(result_queue, call_item.work_id, exception=exc)
  200. else:
  201. _sendback_result(result_queue, call_item.work_id, result=r)
  202. # Liberate the resource as soon as possible, to avoid holding onto
  203. # open files or shared memory that is not needed anymore
  204. del call_item
  205. def _add_call_item_to_queue(pending_work_items,
  206. work_ids,
  207. call_queue):
  208. """Fills call_queue with _WorkItems from pending_work_items.
  209. This function never blocks.
  210. Args:
  211. pending_work_items: A dict mapping work ids to _WorkItems e.g.
  212. {5: <_WorkItem...>, 6: <_WorkItem...>, ...}
  213. work_ids: A queue.Queue of work ids e.g. Queue([5, 6, ...]). Work ids
  214. are consumed and the corresponding _WorkItems from
  215. pending_work_items are transformed into _CallItems and put in
  216. call_queue.
  217. call_queue: A multiprocessing.Queue that will be filled with _CallItems
  218. derived from _WorkItems.
  219. """
  220. while True:
  221. if call_queue.full():
  222. return
  223. try:
  224. work_id = work_ids.get(block=False)
  225. except queue.Empty:
  226. return
  227. else:
  228. work_item = pending_work_items[work_id]
  229. if work_item.future.set_running_or_notify_cancel():
  230. call_queue.put(_CallItem(work_id,
  231. work_item.fn,
  232. work_item.args,
  233. work_item.kwargs),
  234. block=True)
  235. else:
  236. del pending_work_items[work_id]
  237. continue
  238. def _queue_management_worker(executor_reference,
  239. processes,
  240. pending_work_items,
  241. work_ids_queue,
  242. call_queue,
  243. result_queue,
  244. thread_wakeup):
  245. """Manages the communication between this process and the worker processes.
  246. This function is run in a local thread.
  247. Args:
  248. executor_reference: A weakref.ref to the ProcessPoolExecutor that owns
  249. this thread. Used to determine if the ProcessPoolExecutor has been
  250. garbage collected and that this function can exit.
  251. process: A list of the ctx.Process instances used as
  252. workers.
  253. pending_work_items: A dict mapping work ids to _WorkItems e.g.
  254. {5: <_WorkItem...>, 6: <_WorkItem...>, ...}
  255. work_ids_queue: A queue.Queue of work ids e.g. Queue([5, 6, ...]).
  256. call_queue: A ctx.Queue that will be filled with _CallItems
  257. derived from _WorkItems for processing by the process workers.
  258. result_queue: A ctx.SimpleQueue of _ResultItems generated by the
  259. process workers.
  260. thread_wakeup: A _ThreadWakeup to allow waking up the
  261. queue_manager_thread from the main Thread and avoid deadlocks
  262. caused by permanently locked queues.
  263. """
  264. executor = None
  265. def shutting_down():
  266. return (_global_shutdown or executor is None
  267. or executor._shutdown_thread)
  268. def shutdown_worker():
  269. # This is an upper bound on the number of children alive.
  270. n_children_alive = sum(p.is_alive() for p in processes.values())
  271. n_children_to_stop = n_children_alive
  272. n_sentinels_sent = 0
  273. # Send the right number of sentinels, to make sure all children are
  274. # properly terminated.
  275. while n_sentinels_sent < n_children_to_stop and n_children_alive > 0:
  276. for i in range(n_children_to_stop - n_sentinels_sent):
  277. try:
  278. call_queue.put_nowait(None)
  279. n_sentinels_sent += 1
  280. except Full:
  281. break
  282. n_children_alive = sum(p.is_alive() for p in processes.values())
  283. # Release the queue's resources as soon as possible.
  284. call_queue.close()
  285. # If .join() is not called on the created processes then
  286. # some ctx.Queue methods may deadlock on Mac OS X.
  287. for p in processes.values():
  288. p.join()
  289. result_reader = result_queue._reader
  290. wakeup_reader = thread_wakeup._reader
  291. readers = [result_reader, wakeup_reader]
  292. while True:
  293. _add_call_item_to_queue(pending_work_items,
  294. work_ids_queue,
  295. call_queue)
  296. # Wait for a result to be ready in the result_queue while checking
  297. # that all worker processes are still running, or for a wake up
  298. # signal send. The wake up signals come either from new tasks being
  299. # submitted, from the executor being shutdown/gc-ed, or from the
  300. # shutdown of the python interpreter.
  301. worker_sentinels = [p.sentinel for p in processes.values()]
  302. ready = wait(readers + worker_sentinels)
  303. cause = None
  304. is_broken = True
  305. if result_reader in ready:
  306. try:
  307. result_item = result_reader.recv()
  308. is_broken = False
  309. except BaseException as e:
  310. cause = traceback.format_exception(type(e), e, e.__traceback__)
  311. elif wakeup_reader in ready:
  312. is_broken = False
  313. result_item = None
  314. thread_wakeup.clear()
  315. if is_broken:
  316. # Mark the process pool broken so that submits fail right now.
  317. executor = executor_reference()
  318. if executor is not None:
  319. executor._broken = ('A child process terminated '
  320. 'abruptly, the process pool is not '
  321. 'usable anymore')
  322. executor._shutdown_thread = True
  323. executor = None
  324. bpe = BrokenProcessPool("A process in the process pool was "
  325. "terminated abruptly while the future was "
  326. "running or pending.")
  327. if cause is not None:
  328. bpe.__cause__ = _RemoteTraceback(
  329. f"\n'''\n{''.join(cause)}'''")
  330. # All futures in flight must be marked failed
  331. for work_id, work_item in pending_work_items.items():
  332. work_item.future.set_exception(bpe)
  333. # Delete references to object. See issue16284
  334. del work_item
  335. pending_work_items.clear()
  336. # Terminate remaining workers forcibly: the queues or their
  337. # locks may be in a dirty state and block forever.
  338. for p in processes.values():
  339. p.terminate()
  340. shutdown_worker()
  341. return
  342. if isinstance(result_item, int):
  343. # Clean shutdown of a worker using its PID
  344. # (avoids marking the executor broken)
  345. assert shutting_down()
  346. p = processes.pop(result_item)
  347. p.join()
  348. if not processes:
  349. shutdown_worker()
  350. return
  351. elif result_item is not None:
  352. work_item = pending_work_items.pop(result_item.work_id, None)
  353. # work_item can be None if another process terminated (see above)
  354. if work_item is not None:
  355. if result_item.exception:
  356. work_item.future.set_exception(result_item.exception)
  357. else:
  358. work_item.future.set_result(result_item.result)
  359. # Delete references to object. See issue16284
  360. del work_item
  361. # Delete reference to result_item
  362. del result_item
  363. # Check whether we should start shutting down.
  364. executor = executor_reference()
  365. # No more work items can be added if:
  366. # - The interpreter is shutting down OR
  367. # - The executor that owns this worker has been collected OR
  368. # - The executor that owns this worker has been shutdown.
  369. if shutting_down():
  370. try:
  371. # Flag the executor as shutting down as early as possible if it
  372. # is not gc-ed yet.
  373. if executor is not None:
  374. executor._shutdown_thread = True
  375. # Since no new work items can be added, it is safe to shutdown
  376. # this thread if there are no pending work items.
  377. if not pending_work_items:
  378. shutdown_worker()
  379. return
  380. except Full:
  381. # This is not a problem: we will eventually be woken up (in
  382. # result_queue.get()) and be able to send a sentinel again.
  383. pass
  384. executor = None
  385. _system_limits_checked = False
  386. _system_limited = None
  387. def _check_system_limits():
  388. global _system_limits_checked, _system_limited
  389. if _system_limits_checked:
  390. if _system_limited:
  391. raise NotImplementedError(_system_limited)
  392. _system_limits_checked = True
  393. try:
  394. nsems_max = os.sysconf("SC_SEM_NSEMS_MAX")
  395. except (AttributeError, ValueError):
  396. # sysconf not available or setting not available
  397. return
  398. if nsems_max == -1:
  399. # indetermined limit, assume that limit is determined
  400. # by available memory only
  401. return
  402. if nsems_max >= 256:
  403. # minimum number of semaphores available
  404. # according to POSIX
  405. return
  406. _system_limited = ("system provides too few semaphores (%d"
  407. " available, 256 necessary)" % nsems_max)
  408. raise NotImplementedError(_system_limited)
  409. def _chain_from_iterable_of_lists(iterable):
  410. """
  411. Specialized implementation of itertools.chain.from_iterable.
  412. Each item in *iterable* should be a list. This function is
  413. careful not to keep references to yielded objects.
  414. """
  415. for element in iterable:
  416. element.reverse()
  417. while element:
  418. yield element.pop()
  419. class BrokenProcessPool(_base.BrokenExecutor):
  420. """
  421. Raised when a process in a ProcessPoolExecutor terminated abruptly
  422. while a future was in the running state.
  423. """
  424. class ProcessPoolExecutor(_base.Executor):
  425. def __init__(self, max_workers=None, mp_context=None,
  426. initializer=None, initargs=()):
  427. """Initializes a new ProcessPoolExecutor instance.
  428. Args:
  429. max_workers: The maximum number of processes that can be used to
  430. execute the given calls. If None or not given then as many
  431. worker processes will be created as the machine has processors.
  432. mp_context: A multiprocessing context to launch the workers. This
  433. object should provide SimpleQueue, Queue and Process.
  434. initializer: A callable used to initialize worker processes.
  435. initargs: A tuple of arguments to pass to the initializer.
  436. """
  437. _check_system_limits()
  438. if max_workers is None:
  439. self._max_workers = os.cpu_count() or 1
  440. if sys.platform == 'win32':
  441. self._max_workers = min(_MAX_WINDOWS_WORKERS,
  442. self._max_workers)
  443. else:
  444. if max_workers <= 0:
  445. raise ValueError("max_workers must be greater than 0")
  446. elif (sys.platform == 'win32' and
  447. max_workers > _MAX_WINDOWS_WORKERS):
  448. raise ValueError(
  449. f"max_workers must be <= {_MAX_WINDOWS_WORKERS}")
  450. self._max_workers = max_workers
  451. if mp_context is None:
  452. mp_context = mp.get_context()
  453. self._mp_context = mp_context
  454. if initializer is not None and not callable(initializer):
  455. raise TypeError("initializer must be a callable")
  456. self._initializer = initializer
  457. self._initargs = initargs
  458. # Management thread
  459. self._queue_management_thread = None
  460. # Map of pids to processes
  461. self._processes = {}
  462. # Shutdown is a two-step process.
  463. self._shutdown_thread = False
  464. self._shutdown_lock = threading.Lock()
  465. self._broken = False
  466. self._queue_count = 0
  467. self._pending_work_items = {}
  468. # Create communication channels for the executor
  469. # Make the call queue slightly larger than the number of processes to
  470. # prevent the worker processes from idling. But don't make it too big
  471. # because futures in the call queue cannot be cancelled.
  472. queue_size = self._max_workers + EXTRA_QUEUED_CALLS
  473. self._call_queue = _SafeQueue(
  474. max_size=queue_size, ctx=self._mp_context,
  475. pending_work_items=self._pending_work_items)
  476. # Killed worker processes can produce spurious "broken pipe"
  477. # tracebacks in the queue's own worker thread. But we detect killed
  478. # processes anyway, so silence the tracebacks.
  479. self._call_queue._ignore_epipe = True
  480. self._result_queue = mp_context.SimpleQueue()
  481. self._work_ids = queue.Queue()
  482. # _ThreadWakeup is a communication channel used to interrupt the wait
  483. # of the main loop of queue_manager_thread from another thread (e.g.
  484. # when calling executor.submit or executor.shutdown). We do not use the
  485. # _result_queue to send the wakeup signal to the queue_manager_thread
  486. # as it could result in a deadlock if a worker process dies with the
  487. # _result_queue write lock still acquired.
  488. self._queue_management_thread_wakeup = _ThreadWakeup()
  489. def _start_queue_management_thread(self):
  490. if self._queue_management_thread is None:
  491. # When the executor gets garbarge collected, the weakref callback
  492. # will wake up the queue management thread so that it can terminate
  493. # if there is no pending work item.
  494. def weakref_cb(_,
  495. thread_wakeup=self._queue_management_thread_wakeup):
  496. mp.util.debug('Executor collected: triggering callback for'
  497. ' QueueManager wakeup')
  498. thread_wakeup.wakeup()
  499. # Start the processes so that their sentinels are known.
  500. self._adjust_process_count()
  501. self._queue_management_thread = threading.Thread(
  502. target=_queue_management_worker,
  503. args=(weakref.ref(self, weakref_cb),
  504. self._processes,
  505. self._pending_work_items,
  506. self._work_ids,
  507. self._call_queue,
  508. self._result_queue,
  509. self._queue_management_thread_wakeup),
  510. name="QueueManagerThread")
  511. self._queue_management_thread.daemon = True
  512. self._queue_management_thread.start()
  513. _threads_wakeups[self._queue_management_thread] = \
  514. self._queue_management_thread_wakeup
  515. def _adjust_process_count(self):
  516. for _ in range(len(self._processes), self._max_workers):
  517. p = self._mp_context.Process(
  518. target=_process_worker,
  519. args=(self._call_queue,
  520. self._result_queue,
  521. self._initializer,
  522. self._initargs))
  523. p.start()
  524. self._processes[p.pid] = p
  525. def submit(*args, **kwargs):
  526. if len(args) >= 2:
  527. self, fn, *args = args
  528. elif not args:
  529. raise TypeError("descriptor 'submit' of 'ProcessPoolExecutor' object "
  530. "needs an argument")
  531. elif 'fn' in kwargs:
  532. fn = kwargs.pop('fn')
  533. self, *args = args
  534. else:
  535. raise TypeError('submit expected at least 1 positional argument, '
  536. 'got %d' % (len(args)-1))
  537. with self._shutdown_lock:
  538. if self._broken:
  539. raise BrokenProcessPool(self._broken)
  540. if self._shutdown_thread:
  541. raise RuntimeError('cannot schedule new futures after shutdown')
  542. if _global_shutdown:
  543. raise RuntimeError('cannot schedule new futures after '
  544. 'interpreter shutdown')
  545. f = _base.Future()
  546. w = _WorkItem(f, fn, args, kwargs)
  547. self._pending_work_items[self._queue_count] = w
  548. self._work_ids.put(self._queue_count)
  549. self._queue_count += 1
  550. # Wake up queue management thread
  551. self._queue_management_thread_wakeup.wakeup()
  552. self._start_queue_management_thread()
  553. return f
  554. submit.__doc__ = _base.Executor.submit.__doc__
  555. def map(self, fn, *iterables, timeout=None, chunksize=1):
  556. """Returns an iterator equivalent to map(fn, iter).
  557. Args:
  558. fn: A callable that will take as many arguments as there are
  559. passed iterables.
  560. timeout: The maximum number of seconds to wait. If None, then there
  561. is no limit on the wait time.
  562. chunksize: If greater than one, the iterables will be chopped into
  563. chunks of size chunksize and submitted to the process pool.
  564. If set to one, the items in the list will be sent one at a time.
  565. Returns:
  566. An iterator equivalent to: map(func, *iterables) but the calls may
  567. be evaluated out-of-order.
  568. Raises:
  569. TimeoutError: If the entire result iterator could not be generated
  570. before the given timeout.
  571. Exception: If fn(*args) raises for any values.
  572. """
  573. if chunksize < 1:
  574. raise ValueError("chunksize must be >= 1.")
  575. results = super().map(partial(_process_chunk, fn),
  576. _get_chunks(*iterables, chunksize=chunksize),
  577. timeout=timeout)
  578. return _chain_from_iterable_of_lists(results)
  579. def shutdown(self, wait=True):
  580. with self._shutdown_lock:
  581. self._shutdown_thread = True
  582. if self._queue_management_thread:
  583. # Wake up queue management thread
  584. self._queue_management_thread_wakeup.wakeup()
  585. if wait:
  586. self._queue_management_thread.join()
  587. # To reduce the risk of opening too many files, remove references to
  588. # objects that use file descriptors.
  589. self._queue_management_thread = None
  590. if self._call_queue is not None:
  591. self._call_queue.close()
  592. if wait:
  593. self._call_queue.join_thread()
  594. self._call_queue = None
  595. self._result_queue = None
  596. self._processes = None
  597. if self._queue_management_thread_wakeup:
  598. self._queue_management_thread_wakeup.close()
  599. self._queue_management_thread_wakeup = None
  600. shutdown.__doc__ = _base.Executor.shutdown.__doc__
  601. atexit.register(_python_exit)