logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

process.py (30201B)


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