"""Implements ProcessPoolExecutor.

The following diagram and text describe the data-flow through the system:

|======================= In-process =====================|== Out-of-process ==|

+----------+     +----------+       +--------+     +-----------+    +---------+
|          |  => | Work Ids |       |        |     | Call Q    |    | Process |
|          |     +----------+       |        |     +-----------+    |  Pool   |
|          |     | ...      |       |        |     | ...       |    +---------+
|          |     | 6        |    => |        |  => | 5, call() | => |         |
|          |     | 7        |       |        |     | ...       |    |         |
| Process  |     | ...      |       | Local  |     +-----------+    | Process |
|  Pool    |     +----------+       | Worker |                      |  #1..n  |
| Executor |                        | Thread |                      |         |
|          |     +----------- +     |        |     +-----------+    |         |
|          | <=> | Work Items | <=> |        | <=  | Result Q  | <= |         |
|          |     +------------+     |        |     +-----------+    |         |
|          |     | 6: call()  |     |        |     | ...       |    |         |
|          |     |    future  |     |        |     | 4, result |    |         |
|          |     | ...        |     |        |     | 3, except |    |         |
+----------+     +------------+     +--------+     +-----------+    +---------+

Executor.submit() called:
- creates a uniquely numbered _WorkItem and adds it to the "Work Items" dict
- adds the id of the _WorkItem to the "Work Ids" queue

Local worker thread:
- reads work ids from the "Work Ids" queue and looks up the corresponding
  WorkItem from the "Work Items" dict: if the work item has been cancelled then
  it is simply removed from the dict, otherwise it is repackaged as a
  _CallItem and put in the "Call Q". New _CallItems are put in the "Call Q"
  until "Call Q" is full. NOTE: the size of the "Call Q" is kept small because
  calls placed in the "Call Q" can no longer be cancelled with Future.cancel().
- reads _ResultItems from "Result Q", updates the future stored in the
  "Work Items" dict and deletes the dict entry

Process #1..n:
- reads _CallItems from "Call Q", executes the calls, and puts the resulting
  _ResultItems in "Result Q"
"""

# Copyright 2009 Brian Quinlan. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.

# This import is required to load the multiprocessing.connection submodule
# so that it can be accessed later as `mp.connection`

        # Please note that we do not take the shutdown lock when
        # calling clear() (to avoid deadlocking) so this method can
        # only be called safely from the same thread as all calls to
        # clear() even if you hold the shutdown lock. Otherwise we
        # might try to read from the closed pipe.
        
        # call not protected by ProcessPoolExecutor._shutdown_lock
        
# Register for `_python_exit()` to be called just before joining all
# non-daemon threads. This is used instead of `atexit.register()` for
# compatibility with subinterpreters, which no longer support daemon threads.
# See bpo-39812 for context.

# Controls how many more calls than processes will be queued in the call queue.
# A smaller number will mean that processes spend more time idle waiting for
# work while a larger number will make Future.cancel() succeed less frequently
# (Futures in the call queue cannot be cancelled).

# On Windows, WaitForMultipleObjects is used to wait for processes to finish.
# It can wait on, at most, 63 objects. There is an overhead of two objects:
# - the result queue reader
# - the thread wakeup reader

# Hack to embed stringification of remote traceback in local traceback

        # Traceback object needs to be garbage-collected as its frames
        # contain references to all the objects in the exception scope
        
"""Safe Queue set exception to the future object linked to a job"""

            # work_item can be None if another process terminated. In this
            # case, the executor_manager_thread fails all work_items
            # with BrokenProcessPool
            
""" Processes a chunk of an iterable passed to map.

    Runs the function passed to map() on a chunk of the
    iterable passed to map.

    This function is run in a separate process.

    """

"""Evaluates calls from call_queue and places the results in result_queue.

    This worker is run in a separate process.

    Args:
        call_queue: A ctx.Queue of _CallItems that will be read and
            evaluated by the worker.
        result_queue: A ctx.Queue of _ResultItems that will written
            to by the worker.
        initializer: A callable initializer, or None
        initargs: A tuple of args for the initializer
    """

            # The parent will notice that the process stopped and
            # mark the pool broken
            
        # Liberate the resource as soon as possible, to avoid holding onto
        # open files or shared memory that is not needed anymore
        
"""Manages the communication between this process and the worker processes.

    The manager is run in a local thread.

    Args:
        executor: A reference to the ProcessPoolExecutor that owns
            this thread. A weakref will be own by the manager as well as
            references to internal objects used to introspect the state of
            the executor.
    """

        # Store references to necessary internals of the executor.

        # A _ThreadWakeup to allow waking up the queue_manager_thread from the
        # main Thread and avoid deadlocks caused by permanently locked queues.
        
        # A weakref.ref to the ProcessPoolExecutor that owns this thread. Used
        # to determine if the ProcessPoolExecutor has been garbage collected
        # and that the manager can exit.
        # When the executor gets garbage collected, the weakref callback
        # will wake up the queue management thread so that it can terminate
        # if there is no pending work item.
        
        # A list of the ctx.Process instances used as workers.
        
        # A ctx.Queue that will be filled with _CallItems derived from
        # _WorkItems for processing by the process workers.
        
        # A ctx.SimpleQueue of _ResultItems generated by the process workers.
        
        # A queue.Queue of work ids e.g. Queue([5, 6, ...]).
        
        # Maximum number of tasks a worker process can execute before
        # exiting safely
        
        # A dict mapping work ids to _WorkItems e.g.
        #     {5: <_WorkItem...>, 6: <_WorkItem...>, ...}
        
            # gh-109047: During Python finalization, self.call_queue.put()
            # creation of a thread can fail with RuntimeError.
            
                # Delete reference to result_item to avoid keeping references
                # while waiting on new results.
                
                # When only canceled futures remain in pending_work_items, our
                # next call to wait_result_broken_or_wakeup would hang forever.
                # This makes sure we have some running futures or none at all.
                
                # Since no new work items can be added, it is safe to shutdown
                # this thread if there are no pending work items.
                
        # Fills call_queue with _WorkItems from pending_work_items.
        # This function never blocks.
        
        # Wait for a result to be ready in the result_queue while checking
        # that all worker processes are still running, or for a wake up
        # signal send. The wake up signals come either from new tasks being
        # submitted, from the executor being shutdown/gc-ed, or from the
        # shutdown of the python interpreter.
        
        # No need to hold the _shutdown_lock here because:
        # 1. we're the only thread to use the wakeup reader
        # 2. we're also the only thread to call thread_wakeup.close()
        # 3. we want to avoid a possible deadlock when both reader and writer
        #    would block (gh-105829)
        
        # Process the received a result_item. This can be either the PID of a
        # worker that exited gracefully or a _ResultItem

            # Clean shutdown of a worker using its PID
            # (avoids marking the executor broken)
            
            # Received a _ResultItem so mark the future as completed.
            
            # work_item can be None if another process terminated (see above)
            
        # Check whether we should start shutting down the executor.
        
        # No more work items can be added if:
        #   - The interpreter is shutting down OR
        #   - The executor that owns this worker has been collected OR
        #   - The executor that owns this worker has been shutdown.
        
        # Terminate the executor because it is in a broken state. The cause
        # argument can be used to display more information on the error that
        # lead the executor into becoming broken.

        # Mark the process pool broken so that submits fail right now.
        
        # All pending tasks are to be marked failed with the following
        # BrokenProcessPool error
        
                # set_exception() fails if the future is cancelled: ignore it.
                # Trying to check if the future is cancelled before calling
                # set_exception() would leave a race condition if the future is
                # cancelled between the check and set_exception().
                
            # Delete references to object. See issue16284
            
        # Terminate remaining workers forcibly: the queues or their
        # locks may be in a dirty state and block forever.
        
        # Flag the executor as shutting down and cancel remaining tasks if
        # requested as early as possible if it is not gc-ed yet.
        
            # Cancel pending work items if requested.
            
                # Cancel all pending futures and update pending_work_items
                # to only have futures that are currently running.
                
                # Drain work_ids_queue since we no longer need to
                # add items to the call queue.
                
                # Make sure we do this only once to not waste time looping
                # on running processes over and over.
                
        # Send the right number of sentinels, to make sure all children are
        # properly terminated.
        
        # If broken, call_queue was closed and so can no longer be used.
        
        # Release the queue's resources as soon as possible.
        
        # If .join() is not called on the created processes then
        # some ctx.Queue methods may deadlock on Mac OS X.
        
        # This is an upper bound on the number of children alive.
        
"This Python build lacks multiprocessing.synchronize, usually due "

        # sysconf not available or setting not available
        
        # indetermined limit, assume that limit is determined
        # by available memory only
        
        # minimum number of semaphores available
        # according to POSIX
        
"""
    Specialized implementation of itertools.chain.from_iterable.
    Each item in *iterable* should be a list.  This function is
    careful not to keep references to yielded objects.
    """

"""
    Raised when a process in a ProcessPoolExecutor terminated abruptly
    while a future was in the running state.
    """

"""Initializes a new ProcessPoolExecutor instance.

        Args:
            max_workers: The maximum number of processes that can be used to
                execute the given calls. If None or not given then as many
                worker processes will be created as the machine has processors.
            mp_context: A multiprocessing context to launch the workers created
                using the multiprocessing.get_context('start method') API. This
                object should provide SimpleQueue, Queue and Process.
            initializer: A callable used to initialize worker processes.
            initargs: A tuple of arguments to pass to the initializer.
            max_tasks_per_child: The maximum number of tasks a worker process
                can complete before it will exit and be replaced with a fresh
                worker process. The default of None means worker process will
                live as long as the executor. Requires a non-'fork' mp_context
                start method. When given, we default to using 'spawn' if no
                mp_context is supplied.
        """

        # https://github.com/python/cpython/issues/90622
        
                # https://github.com/python/cpython/issues/90622
                
        # _ThreadWakeup is a communication channel used to interrupt the wait
        # of the main loop of executor_manager_thread from another thread (e.g.
        # when calling executor.submit or executor.shutdown). We do not use the
        # _result_queue to send wakeup signals to the executor_manager_thread
        # as it could result in a deadlock if a worker process dies with the
        # _result_queue write lock still acquired.
        #
        # _shutdown_lock must be locked to access _ThreadWakeup.close() and
        # .wakeup(). Care must also be taken to not call clear or close from
        # more than one thread since _ThreadWakeup.clear() is not protected by
        # the _shutdown_lock
        
        # Create communication channels for the executor
        # Make the call queue slightly larger than the number of processes to
        # prevent the worker processes from idling. But don't make it too big
        # because futures in the call queue cannot be cancelled.
        
        # Killed worker processes can produce spurious "broken pipe"
        # tracebacks in the queue's own worker thread. But we detect killed
        # processes anyway, so silence the tracebacks.
        
            # Start the processes so that their sentinels are known.
            
        # if there's an idle process, we don't need to spawn a new one.
        
            # Assertion disabled as this codepath is also used to replace a
            # worker that unexpectedly dies, even when using the 'fork' start
            # method. That means there is still a potential deadlock bug. If a
            # 'fork' mp_context worker dies, we'll be forking a new one when
            # we know a thread is running (self._executor_manager_thread).
            #assert self._safe_to_dynamically_spawn_children or not self._executor_manager_thread, 'https://github.com/python/cpython/issues/90622'
            
"""Returns an iterator equivalent to map(fn, iter).

        Args:
            fn: A callable that will take as many arguments as there are
                passed iterables.
            timeout: The maximum number of seconds to wait. If None, then there
                is no limit on the wait time.
            chunksize: If greater than one, the iterables will be chopped into
                chunks of size chunksize and submitted to the process pool.
                If set to one, the items in the list will be sent one at a time.

        Returns:
            An iterator equivalent to: map(func, *iterables) but the calls may
            be evaluated out-of-order.

        Raises:
            TimeoutError: If the entire result iterator could not be generated
                before the given timeout.
            Exception: If fn(*args) raises for any values.
        """

                # Wake up queue management thread
                
        # To reduce the risk of opening too many files, remove references to
        # objects that use file descriptors.
        
    def __init__(self, work_id, exception=None, result=None, exit_pid=None):

    """Safe Queue set exception to the future object linked to a job"""

    def __init__(self, max_size=0, *, ctx, pending_work_items, shutdown_lock,

            e.__cause__ = _RemoteTraceback('\n"""\n{}"""'.format(''.join(tb)))

            work_item = self.pending_work_items.pop(obj.work_id, None)

def _sendback_result(result_queue, work_id, result=None, exception=None,

                                     exception=exception, exit_pid=exit_pid))

def _process_worker(call_queue, result_queue, initializer, initargs, max_tasks=None):

    """Evaluates calls from call_queue and places the results in result_queue.

            _base.LOGGER.critical('Exception in initializer:', exc_info=True)

            r = call_item.fn(*call_item.args, **call_item.kwargs)

            _sendback_result(result_queue, call_item.work_id, exception=exc,

            _sendback_result(result_queue, call_item.work_id, result=r,

    """Manages the communication between this process and the worker processes.

        self.thread_wakeup = executor._executor_manager_thread_wakeup

            mp.util.debug('Executor collected: triggering callback for'

        self.executor_reference = weakref.ref(executor, weakref_cb)

        self.max_tasks_per_child = executor._max_tasks_per_child

            result_item, is_broken, cause = self.wait_result_broken_or_wakeup()

                process_exited = result_item.exit_pid is not None

                    p = self.processes.pop(result_item.exit_pid)

                        executor._idle_worker_semaphore.release()

                if work_item.future.set_running_or_notify_cancel():

                                                  work_item.fn,

                                                  work_item.args,

                                                  work_item.kwargs),

        worker_sentinels = [p.sentinel for p in list(self.processes.values())]

            work_item = self.pending_work_items.pop(result_item.work_id, None)

                    work_item.future.set_exception(result_item.exception)

                    work_item.future.set_result(result_item.result)

                                'abruptly, the process pool is not '

        bpe = BrokenProcessPool("A process in the process pool was "

                                "terminated abruptly while the future was "

        for work_id, work_item in self.pending_work_items.items():

                for work_id, work_item in self.pending_work_items.items():

                        new_pending_work_items[work_id] = work_item

                self.pending_work_items = new_pending_work_items

            for i in range(n_children_to_stop - n_sentinels_sent):

        return sum(p.is_alive() for p in self.processes.values())

            "This Python build lacks multiprocessing.synchronize, usually due "

            "to named semaphores being unavailable on this platform."

    _system_limited = ("system provides too few semaphores (%d"

                       " available, 256 necessary)" % nsems_max)

                 initializer=None, initargs=(), *, max_tasks_per_child=None):

                raise ValueError("max_workers must be greater than 0")

                    f"max_workers must be <= {_MAX_WINDOWS_WORKERS}")

                self._mp_context.get_start_method(allow_none=False) != "fork")

        if initializer is not None and not callable(initializer):

                raise TypeError("max_tasks_per_child must be an integer")

                raise ValueError("max_tasks_per_child must be >= 1")

            if self._mp_context.get_start_method(allow_none=False) == "fork":

                raise ValueError("max_tasks_per_child is incompatible with"

                                 " the 'fork' multiprocessing start method;"

                                 " supply a different mp_context.")

            thread_wakeup=self._executor_manager_thread_wakeup)

            if not self._safe_to_dynamically_spawn_children:  # ie, using fork.

            self._executor_manager_thread = _ExecutorManagerThread(self)

            _threads_wakeups[self._executor_manager_thread] = \

        if self._idle_worker_semaphore.acquire(blocking=False):

                'Processes cannot be fork()ed after the thread has started, '

                'deadlock in the child processes could result.')

        for _ in range(len(self._processes), self._max_workers):

                raise RuntimeError('cannot schedule new futures after shutdown')

                raise RuntimeError('cannot schedule new futures after '

                              _get_chunks(*iterables, chunksize=chunksize),

            if self._executor_manager_thread_wakeup is not None: