o ?Og|@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)Zduplex)_closedmpZPipe_reader_writerselfr A/opt/alt/python310/lib64/python3.10/concurrent/futures/process.py__init__Csz_ThreadWakeup.__init__cCs(|jsd|_|j|jdSdSNT)rr closerr r r r rGs  z_ThreadWakeup.closecCs|js |jddSdS)N)rr Z send_bytesr r r r wakeupMsz_ThreadWakeup.wakeupcCs0|js|jr|j|jsdSdSdSN)rrZpollZ recv_bytesr r r r clearQs   z_ThreadWakeup.clearN)__name__ __module__ __qualname__rrrrr r r r rBs  rcCs@datt}|D]\}}|q |D]\}}|qdSr)_global_shutdownlist_threads_wakeupsitemsrjoin)r_ thread_wakeuptr r r _python_exitWs     r =c@eZdZddZddZdS)_RemoteTracebackcCs ||_dSrtb)r r&r r r rws z_RemoteTraceback.__init__cCs|jSrr%r r r r __str__ysz_RemoteTraceback.__str__N)rrrrr'r r r r r$vs r$c@r#)_ExceptionWithTracebackcCs8tt|||}d|}||_d|j_d||_dS)Nz """ %s""") tracebackformat_exceptiontyperexc __traceback__r&)r r-r&r r r r}s  z _ExceptionWithTraceback.__init__cCst|j|jffSr) _rebuild_excr-r&r r r r __reduce__sz"_ExceptionWithTraceback.__reduce__N)rrrrr0r r r r r(|s r(cCst||_|Sr)r$ __cause__)r-r&r r r r/s r/c@eZdZddZdS) _WorkItemcC||_||_||_||_dSr)futurefnargskwargs)r r5r6r7r8r r r r z_WorkItem.__init__Nrrrrr r r r r3 r3c@seZdZdddZdS) _ResultItemNcCs||_||_||_dSr)work_id exceptionresult)r r=r>r?r r r rs z_ResultItem.__init__NNr:r r r r r<sr<c@r2) _CallItemcCr4r)r=r6r7r8)r r=r6r7r8r r r rr9z_CallItem.__init__Nr:r r r r rAr;rAcs.eZdZdZdfdd ZfddZZS) _SafeQueuez=Safe Queue set exception to the future object linked to a jobrcs&||_||_||_tj||ddS)N)ctx)pending_work_items shutdown_lockrsuperr)r max_sizerCrDrEr __class__r r rsz_SafeQueue.__init__cst|trHtt|||j}tdd||_ |j |j d}|j |jWdn1s5wY|durF|j|dSdSt||dS)Nz """ {}"""r)) isinstancerAr*r+r,r.r$formatrr1rDpopr=rErrr5 set_exceptionrF_on_queue_feeder_error)r eobjr& work_itemrHr r rNs  z!_SafeQueue._on_queue_feeder_error)r)rrr__doc__rrN __classcell__r r rHr rBsrBcgs,t|} tt||}|sdS|Vq)z, Iterates over zip()ed iterables in chunks. TN)ziptuple itertoolsislice) chunksize iterablesitchunkr r r _get_chunkssr\csfdd|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|]}|qSr r ).0r7r6r r sz"_process_chunk..r )r6r[r r^r _process_chunks r`c Cs`z |t|||dWdSty/}zt||j}|t||dWYd}~dSd}~ww)z.Safely send back the given result or exception)r?r>r>N)putr< BaseExceptionr(r.) result_queuer=r?r>rOr-r r r _sendback_results   rec 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_infoblockra)r?)rcrZLOGGERZcriticalgetrbosgetpidr6r7r8r(r.rer=) call_queuerd initializerinitargsZ call_itemrrOr-r r r _process_workers.     rpcspeZdZdZfddZddZddZdd 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)rrrEr r r weakref_cbs  "z3_ExecutorManagerThread.__init__..weakref_cb)_executor_manager_thread_wakeupr_shutdown_lockrEweakrefrefexecutor_reference _processes processes _call_queuerl _result_queuerd _work_idswork_ids_queue_pending_work_itemsrDrFr)r executorrtrHr r rs  z_ExecutorManagerThread.__init__cCs ||\}}}|r||dS|dur-||~|}|dur,|j~|rB|||j sB| dSqr) add_call_item_to_queuewait_result_broken_or_wakeupterminate_brokenprocess_result_itemry_idle_worker_semaphorereleaseis_shutting_downflag_executor_shutting_downrDjoin_executor_internals)r result_item is_brokencauserr r r run:s(   z_ExecutorManagerThread.runcCs| |jrdSz |jjdd}Wn tjyYdSw|j|}|jr8|jj t ||j |j |j ddn|j|=qq)NTFrg)rlZfullrriqueueEmptyrDr5Zset_running_or_notify_cancelrbrAr6r7r8)r r=rQr r r r_s(    z-_ExecutorManagerThread.add_call_item_to_queuec Cs|jj}|jj}||g}ddt|jD}tj||}d}d}d}||vrOz| }d}Wn"t yN} zt t | | | j}WYd} ~ n d} ~ ww||vrUd}|j |jWdn1shwY|||fS)NcSsg|]}|jqSr )Zsentinelr]pr r r r_szG_ExecutorManagerThread.wait_result_broken_or_wakeup..TF)rdrrrr{valuesrZ connectionwaitZrecvrcr*r+r,r.rEr) r Z result_readerZ wakeup_readerZreadersZworker_sentinelsZreadyrrrrOr r r rvs,   z3_ExecutorManagerThread.wait_result_broken_or_wakeupcCszt|tr|j|}||js|dSdS|j|jd}|dur;|jr2|j |jdS|j |j dSdSr) rJintr{rLrrrDr=r>r5rMZ set_resultr?)r rrrQr r r rs  z*_ExecutorManagerThread.process_result_itemcCs|}tp |dup |jSr)ryr_shutdown_thread)r rr r r rs 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''')ry_brokenrBrokenProcessPoolr$rr1rDrr5rMrr{rZ terminater)r rrZbper=rQrr r r rs"    z'_ExecutorManagerThread.terminate_brokencCs|}|dur?d|_|jrAi}|jD] \}}|js"|||<q||_ z|jWn t j y8Ynwq'd|_dSdSdS)NTF) ryr_cancel_pending_futuresrDrr5ZcancelrZ get_nowaitrr)r rZnew_pending_work_itemsr=rQr r r rs(  z2_ExecutorManagerThread.flag_executor_shutting_downc Cs|}d}||kr<|dkr>t||D]}z |jd|d7}Wqtjy/Ynw||kr@|dksdSdSdSdS)Nrr!)get_n_children_aliverangerlZ put_nowaitrZFull)r Zn_children_to_stopZn_sentinels_sentir r r shutdown_workerss    z'_ExecutorManagerThread.shutdown_workerscCsh||j|j|j |jWdn1s!wY|jD]}|q+dSr) rrlrZ join_threadrErr{rrr rr r r rs    z._ExecutorManagerThread.join_executor_internalscCstdd|jDS)Ncss|]}|VqdSr)Zis_aliverr r r sz>_ExecutorManagerThread.get_n_children_alive..)sumr{rr r r r rsz+_ExecutorManagerThread.get_n_children_alive)rrrrRrrrrrrrrrrrrSr r rHr rqs +% & rqc 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_limitedNotImplementedErrorZmultiprocessing.synchronize ImportErrorrjsysconfAttributeError ValueError)multiprocessingZ nsems_maxr r r _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)reverserL)iterableZelementr r r _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)rrrrRr r r r rEsrcseZdZ  dddZddZddZd d Zd d Zd dZe j jj e_ dddfdd Z dddddZ e j j j e _ ZS)ProcessPoolExecutorNr cCsHt|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!Zwin32rz"max_workers must be greater than 0zmax_workers must be <= F)Z allow_noneforkzinitializer must be a callable)rGrCrDrErT))rrj cpu_count _max_workerssysplatformmin_MAX_WINDOWS_WORKERSrrZ get_context _mp_contextZget_start_method#_safe_to_dynamically_spawn_childrencallable TypeError _initializer _initargs_executor_manager_threadrzr threadingZLockrvZ Semaphorerr _queue_countrrrruEXTRA_QUEUED_CALLSrBr|Z _ignore_epipeZ SimpleQueuer}rrr~)r Z max_workersZ mp_contextrmrnZ queue_sizer r r rMsZ       zProcessPoolExecutor.__init__cCs@|jdur|js |t||_|j|jt|j<dSdSr)rr_launch_processesrqstartrurr r r r _start_executor_manager_threads    z2ProcessPoolExecutor._start_executor_manager_threadcCs6|jjddr dSt|j}||jkr|dSdS)NF)Zblocking)racquirelenrzr_spawn_process)r Z process_countr r r _adjust_process_counts    z)ProcessPoolExecutor._adjust_process_countcCs$tt|j|jD]}|q dSr)rrrzrr)r rr r r rs z%ProcessPoolExecutor._launch_processescCs8|jjt|j|j|j|jfd}|||j|j <dS)N)targetr7) rZProcessrpr|r}rrrrzpidrr r r rsz"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!)rvrrr RuntimeErrorrrZFuturer3rrr~rbrurrrr)r r6r7r8fwr r r submits$   $zProcessPoolExecutor.submitr!)timeoutrXcs:|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.rX)r)rrFmaprr`r\r)r r6rrXrYZresultsrHr r rs zProcessPoolExecutor.mapTF)cancel_futurescCs|j||_d|_|jdur|jWdn1swY|jdur/|r/|jd|_d|_|jdurA|rA|j d|_d|_ d|_dSr) rvrrrurrrr|r}rrz)r rrr r r shutdowns      zProcessPoolExecutor.shutdown)NNNr )T)rrrrrrrrrrExecutorrRrrrSr r rHr rLs U  rr@)1rR __author__rjZconcurrent.futuresrrrrZmultiprocessing.connectionZmultiprocessing.queuesrrrw functoolsrrVrr*WeakKeyDictionaryrrrr Z_register_atexitrr Exceptionr$r(r/objectr3r<rArBr\r`rerpZThreadrqrrrrZBrokenExecutorrrrr r r r sR*       )