o *g|@sdZdZddlZddlmZddlZddlZddlZddl m Z ddl Z ddl Z ddl mZddlZddlZddlZe ZdaGdd d Zd d Ze ed Zd ZGdddeZGdddZddZGdddeZGdddeZ GdddeZ!Gddde Z"ddZ#ddZ$d.d d!Z%d"d#Z&Gd$d%d%e j'Z(da)da*d&d'Z+d(d)Z,Gd*d+d+ej-Z.Gd,d-d-ej/Z0dS)/a- 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" z"Brian Quinlan (brian@sweetapp.com)N)_base)Queue)partialFc@s,eZdZddZddZddZddZd S) _ThreadWakeupcCsd|_tjdd\|_|_dS)NF)duplex)_closedmpPipe_reader_writerselfr1/usr/lib/python3.10/concurrent/futures/process.py__init__Csz_ThreadWakeup.__init__cCs(|jsd|_|j|jdSdSNT)rr closer r rrrrGs  z_ThreadWakeup.closecCs|js |jddSdS)N)rr send_bytesr rrrwakeupMsz_ThreadWakeup.wakeupcCs0|js|jr|j|jsdSdSdSN)rr poll recv_bytesr rrrclearQs   z_ThreadWakeup.clearN)__name__ __module__ __qualname__rrrrrrrrrBs  rcCs@datt}|D]\}}|q |D]\}}|qdSr)_global_shutdownlist_threads_wakeupsitemsrjoin)r _ thread_wakeuptrrr _python_exitWs     r%=c@eZdZddZddZdS)_RemoteTracebackcCs ||_dSrtb)r r+rrrrws z_RemoteTraceback.__init__cCs|jSrr*r rrr__str__ysz_RemoteTraceback.__str__N)rrrrr,rrrrr)vs r)c@r()_ExceptionWithTracebackcCs8tt|||}d|}||_d|j_d||_dS)Nz """ %s""") tracebackformat_exceptiontyper!exc __traceback__r+)r r2r+rrrr}s  z _ExceptionWithTraceback.__init__cCst|j|jffSr) _rebuild_excr2r+r rrr __reduce__sz"_ExceptionWithTraceback.__reduce__N)rrrrr5rrrrr-|s r-cCst||_|Sr)r) __cause__)r2r+rrrr4s r4c@eZdZddZdS) _WorkItemcC||_||_||_||_dSr)futurefnargskwargs)r r:r;r<r=rrrr z_WorkItem.__init__Nrrrrrrrrr8 r8c@seZdZdddZdS) _ResultItemNcCs||_||_||_dSr)work_id exceptionresult)r rBrCrDrrrrs z_ResultItem.__init__NNr?rrrrrAsrAc@r7) _CallItemcCr9r)rBr;r<r=)r rBr;r<r=rrrrr>z_CallItem.__init__Nr?rrrrrFr@rFcs.eZdZdZdfdd ZfddZZS) _SafeQueuez=Safe Queue set exception to the future object linked to a jobrcs&||_||_||_tj||ddS)N)ctx)pending_work_items shutdown_lockr#superr)r max_sizerHrIrJr# __class__rrrsz_SafeQueue.__init__cst|trHtt|||j}tdd||_ |j |j d}|j |jWdn1s5wY|durF|j|dSdSt||dS)Nz """ {}"""r.) isinstancerFr/r0r1r3r)formatr!r6rIpoprBrJr#rr: set_exceptionrK_on_queue_feeder_error)r eobjr+ work_itemrMrrrSs  z!_SafeQueue._on_queue_feeder_error)r)rrr__doc__rrS __classcell__rrrMrrGsrGcgs,t|} tt||}|sdS|Vq)z, Iterates over zip()ed iterables in chunks. TN)ziptuple itertoolsislice) chunksize iterablesitchunkrrr _get_chunkssracsfdd|DS)z 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. csg|]}|qSrr).0r<r;rr sz"_process_chunk..r)r;r`rrcr_process_chunks rec Cs`z |t|||dWdSty/}zt||j}|t||dWYd}~dSd}~ww)z.Safely send back the given result or exception)rDrCrCN)putrA BaseExceptionr-r3) result_queuerBrDrCrTr2rrr_sendback_results   rjc Cs|durz||WntytjjdddYdSw |jdd}|dur1|tdSz |j|j i|j }Wn ty]}zt ||j }t ||j|dWYd}~nd}~wwt ||j|d~~q)aEvaluates 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 NzException in initializer:T)exc_infoblockrf)rD)rhrLOGGERcriticalgetrgosgetpidr;r<r=r-r3rjrB) call_queueri initializerinitargs call_itemrrTr2rrr_process_workers.     rxcspeZdZdZfddZddZddZdd Zd d Zd d Z ddZ ddZ ddZ ddZ ddZZS)_ExecutorManagerThreadatManages 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. csf|j|_|j|_|j|jfdd}t|||_|j|_|j |_ |j |_ |j |_|j|_tdS)NcSs>tjd| |WddS1swYdS)Nz?Executor collected: triggering callback for QueueManager wakeup)rutildebugr)r"r#rJrrr weakref_cbs  "z3_ExecutorManagerThread.__init__..weakref_cb)_executor_manager_thread_wakeupr#_shutdown_lockrJweakrefrefexecutor_reference _processes processes _call_queuers _result_queueri _work_idswork_ids_queue_pending_work_itemsrIrKr)r executorr|rMrrrs  z_ExecutorManagerThread.__init__cCs ||\}}}|r||dS|dur-||~|}|dur,|j~|rB|||j sB| dSqr) add_call_item_to_queuewait_result_broken_or_wakeupterminate_brokenprocess_result_itemr_idle_worker_semaphorereleaseis_shutting_downflag_executor_shutting_downrIjoin_executor_internals)r result_item is_brokencauserrrrrun:s(   z_ExecutorManagerThread.runcCs| |jrdSz |jjdd}Wn tjyYdSw|j|}|jr8|jj t ||j |j |j ddn|j|=qq)NTFrl)rsfullrrpqueueEmptyrIr:set_running_or_notify_cancelrgrFr;r<r=)r rBrVrrrr_s(    z-_ExecutorManagerThread.add_call_item_to_queuec Cs|jj}|jjr J|jj}||g}ddt|jD}tj ||}d}d}d}||vrUz| }d}Wn"t yT} zt t| | | j}WYd} ~ n d} ~ ww||vr[d}|j |jWdn1snwY|||fS)NcSsg|]}|jqSr)sentinelrbprrrrdszG_ExecutorManagerThread.wait_result_broken_or_wakeup..TF)rir r#rrrvaluesr connectionwaitrecvrhr/r0r1r3rJr) r result_reader wakeup_readerreadersworker_sentinelsreadyrrrrTrrrrvs.    z3_ExecutorManagerThread.wait_result_broken_or_wakeupcCst|tr |s J|j|}||js|dSdS|j|jd}|durA|j r8|j |j dS|j |j dSdSr)rOintrrrQr!rrIrBrCr:rR set_resultrD)r rrrVrrrrs   z*_ExecutorManagerThread.process_result_itemcCs|}tp |dup |jSr)rr_shutdown_thread)r rrrrrs z'_ExecutorManagerThread.is_shutting_downcCs|}|durd|_d|_d}td}|dur$tdd|d|_|jD] \}}|j |~q)|j |j D]}|q?|dS)NzKA child process terminated abruptly, the process pool is not usable anymoreTz^A process in the process pool was terminated abruptly while the future was running or pending.z ''' r.z''')r_brokenrBrokenProcessPoolr)r!r6rIr r:rRrrr terminater)r rrbperBrVrrrrrs"    z'_ExecutorManagerThread.terminate_brokencCs|}|dur?d|_|jrAi}|jD] \}}|js"|||<q||_ z|jWn t j y8Ynwq'd|_dSdSdS)NTF) rr_cancel_pending_futuresrIr r:cancelr get_nowaitrr)r rnew_pending_work_itemsrBrVrrrrs(  z2_ExecutorManagerThread.flag_executor_shutting_downc Cs|}d}||kr<|dkr>t||D]}z |jd|d7}Wqtjy/Ynw||kr@|dksdSdSdSdS)Nrr&)get_n_children_aliverangers put_nowaitrFull)r n_children_to_stopn_sentinels_sentirrrshutdown_workerss    z'_ExecutorManagerThread.shutdown_workerscCsh||j|j|j |jWdn1s!wY|jD]}|q+dSr) rrsr join_threadrJr#rrr!r rrrrrs    z._ExecutorManagerThread.join_executor_internalscCstdd|jDS)Ncss|]}|VqdSr)is_aliverrrr sz>_ExecutorManagerThread.get_n_children_alive..)sumrrr rrrrsz+_ExecutorManagerThread.get_n_children_alive)rrrrWrrrrrrrrrrrrXrrrMrrys +% & ryc Cstrtrttdazddl}Wn tydattwztd}Wn ttfy1YdSw|dkr8dS|dkr>dSd|att)NTrzxThis Python build lacks multiprocessing.synchronize, usually due to named semaphores being unavailable on this platform.SC_SEM_NSEMS_MAXz@system provides too few semaphores (%d available, 256 necessary)) _system_limits_checked_system_limitedNotImplementedErrormultiprocessing.synchronize ImportErrorrqsysconfAttributeError ValueError)multiprocessing nsems_maxrrr_check_system_limitss0  rccs*|D]}||r|V|s qdS)z 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. N)reverserQ)iterableelementrrr_chain_from_iterable_of_lists9s rc@seZdZdZdS)rzy Raised when a process in a ProcessPoolExecutor terminated abruptly while a future was in the running state. N)rrrrWrrrrrEsrcseZdZ  dddZddZddZd d Zd d Zd dZe j jj e_ dddfdd Z dddddZ e j j j e _ ZS)ProcessPoolExecutorNrcCsHt|durtp d|_tjdkrtt|j|_n|dkr#tdtjdkr3|tkr3tdt||_|dur>t }||_ |j j ddd k|_ |durWt|sWtd ||_||_d|_i|_d|_t|_td|_d|_d|_i|_d|_t|_|jt }t!||j |j|j|jd |_"d |j"_#|$|_%t&'|_(dS) aSInitializes 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. 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. Nr&win32rz"max_workers must be greater than 0zmax_workers must be <= F) allow_noneforkzinitializer must be a callable)rLrHrIrJr#T))rrq cpu_count _max_workerssysplatformmin_MAX_WINDOWS_WORKERSrr get_context _mp_contextget_start_method#_safe_to_dynamically_spawn_childrencallable TypeError _initializer _initargs_executor_manager_threadrr threadingLockr~ Semaphorerr _queue_countrrrr}EXTRA_QUEUED_CALLSrGr _ignore_epipe SimpleQueuerrrr)r max_workers mp_contextrtru queue_sizerrrrMsZ       zProcessPoolExecutor.__init__cCs@|jdur|js |t||_|j|jt|j<dSdSr)rr_launch_processesrystartr}rr rrr_start_executor_manager_threads    z2ProcessPoolExecutor._start_executor_manager_threadcCs6|jjddr dSt|j}||jkr|dSdS)NF)blocking)racquirelenrr_spawn_process)r process_countrrr_adjust_process_counts    z)ProcessPoolExecutor._adjust_process_countcCs2|jrJdtt|j|jD]}|qdS)NzhProcesses cannot be fork()ed after the thread has started, deadlock in the child processes could result.)rrrrrr)r r"rrrrs  z%ProcessPoolExecutor._launch_processescCs8|jjt|j|j|j|jfd}|||j|j <dS)N)targetr<) rProcessrxrrrrrrpidrrrrrsz"ProcessPoolExecutor._spawn_processcOs|jN|jr t|j|jrtdtrtdt}t||||}||j |j <|j |j |j d7_ |j |jrD|||WdS1sTwYdS)Nz*cannot schedule new futures after shutdownz6cannot schedule new futures after interpreter shutdownr&)r~rrr RuntimeErrorrrFuturer8rrrrgr}rrrr)r r;r<r=fwrrrsubmits$   $zProcessPoolExecutor.submitr&)timeoutr]cs:|dkrtdtjtt|t|d|i|d}t|S)ajReturns 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. r&zchunksize must be >= 1.r])r)rrKmaprrerar)r r;rr]r^resultsrMrrrs zProcessPoolExecutor.mapTF)cancel_futurescCs|j||_d|_|jdur|jWdn1swY|jdur/|r/|jd|_d|_|jdurA|rA|j d|_d|_ d|_dSr) r~rrr}rrr!rrrr)r rrrrrshutdowns      zProcessPoolExecutor.shutdown)NNNr)T)rrrrrrrrrrExecutorrWrrrXrrrMrrLs U  rrE)1rW __author__rqconcurrent.futuresrrrrmultiprocessing.connectionmultiprocessing.queuesrrr functoolsrr[rr/WeakKeyDictionaryrrrr%_register_atexitrr Exceptionr)r-r4objectr8rArFrGrarerjrxThreadryrrrrBrokenExecutorrrrrrrrsR*       )