a DOgz@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_writerselfr2/usr/lib64/python3.9/concurrent/futures/process.py__init__Csz_ThreadWakeup.__init__cCs$|js d|_|j|jdSNT)rr closer r rrrrGs z_ThreadWakeup.closecCs|js|jddS)N)rr send_bytesr rrrwakeupMsz_ThreadWakeup.wakeupcCs |js|jr|jqdSN)rr poll recv_bytesr rrrclearQs z_ThreadWakeup.clearN)__name__ __module__ __qualname__rrrrrrrrrBsrcCs@datt}|D]\}}|q|D]\}}|q*dSr)_global_shutdownlist_threads_wakeupsitemsrjoin)r _ thread_wakeuptrrr _python_exitWs     r%=c@seZdZddZddZdS)_RemoteTracebackcCs ||_dSrtb)r r*rrrrwsz_RemoteTraceback.__init__cCs|jSrr)r rrr__str__ysz_RemoteTraceback.__str__N)rrrrr+rrrrr(vsr(c@seZdZddZddZdS)_ExceptionWithTracebackcCs8tt|||}d|}||_d|j_d||_dS)Nz """ %s""") tracebackformat_exceptiontyper!exc __traceback__r*)r r1r*rrrr}s  z _ExceptionWithTraceback.__init__cCst|j|jffSr) _rebuild_excr1r*r rrr __reduce__sz"_ExceptionWithTraceback.__reduce__N)rrrrr4rrrrr,|sr,cCst||_|Sr)r( __cause__)r1r*rrrr3s r3c@seZdZddZdS) _WorkItemcCs||_||_||_||_dSr)futurefnargskwargs)r r7r8r9r:rrrrsz_WorkItem.__init__Nrrrrrrrrr6sr6c@seZdZdddZdS) _ResultItemNcCs||_||_||_dSr)work_id exceptionresult)r r=r>r?rrrrsz_ResultItem.__init__)NNr;rrrrr<sr<c@seZdZddZdS) _CallItemcCs||_||_||_||_dSr)r=r8r9r:)r r=r8r9r:rrrrsz_CallItem.__init__Nr;rrrrr@sr@cs.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_sizerBrCrDr# __class__rrrsz_SafeQueue.__init__cst|trtt|||j}tdd||_ |j |j d}|j |jWdn1sj0Y|dur|j|nt||dS)Nz """ {}"""r-) isinstancer@r.r/r0r2r(formatr!r5rCpopr=rDr#rr7 set_exceptionrE_on_queue_feeder_error)r eobjr* work_itemrGrrrMs (z!_SafeQueue._on_queue_feeder_error)r)rrr__doc__rrM __classcell__rrrGrrAsrAcgs,t|}tt||}|s dS|VqdS)z, Iterates over zip()ed iterables in chunks. N)ziptuple itertoolsislice) chunksize iterablesitchunkrrr _get_chunkss r[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|] }|qSrr).0r9r8rr rz"_process_chunk..r)r8rZrr]r_process_chunks r_c Cs`z|t|||dWnBtyZ}z*t||j}|t||dWYd}~n d}~00dS)z.Safely send back the given result or exception)r?r>r>N)putr< BaseExceptionr,r2) result_queuer=r?r>rNr1rrr_sendback_results   rdc Cs|dur:z ||Wn$ty8tjjdddYdS0|jdd}|dur`|tdSz|j|j i|j }Wn@ty}z(t ||j }t ||j|dWYd}~nd}~00t ||j|d~~q:dS)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_infoblockr`)r?)rbrLOGGERcriticalgetraosgetpidr8r9r:r,r2rdr=) call_queuerc initializerinitargs call_itemrrNr1rrr_process_workers$     &rrcspeZdZdZfddZddZddZdd 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||Wdn1s.0YdS)Nz?Executor collected: triggering callback for QueueManager wakeup)rutildebugr)r"r#rDrrr weakref_cbs z3_ExecutorManagerThread.__init__..weakref_cb)_executor_manager_thread_wakeupr#_shutdown_lockrDweakrefrefexecutor_reference _processes processes _call_queuerm _result_queuerc _work_idswork_ids_queue_pending_work_itemsrCrEr)r executorrvrGrrrs  z_ExecutorManagerThread.__init__cCs||\}}}|r(||dS|durX||~|}|durV|j~|r||j s| dSqdSr) add_call_item_to_queuewait_result_broken_or_wakeupterminate_brokenprocess_result_itemr{_idle_worker_semaphorereleaseis_shutting_downflag_executor_shutting_downrCjoin_executor_internals)r result_item is_brokencauserrrrrun:s"   z_ExecutorManagerThread.runcCs~|jrdSz|jjdd}Wntjy6YdS0|j|}|jrn|jj t ||j |j |j ddq|j|=qqdS)NFrfT)rmfullrrjqueueEmptyrCr7set_running_or_notify_cancelrar@r8r9r:)r r=rPrrrrZs"    z-_ExecutorManagerThread.add_call_item_to_queuec Cs|jj}|jjrJ|jj}||g}ddt|jD}tj ||}d}d}d}||vrz| }d}Wqt y} z t t| | | j}WYd} ~ qd} ~ 00n ||vrd}|j|jWdn1s0Y|||fS)NcSsg|] }|jqSr)sentinelr\prrrr^{rzG_ExecutorManagerThread.wait_result_broken_or_wakeup..TF)rcr r#rrr}valuesr connectionwaitrecvrbr.r/r0r2rDr) r result_reader wakeup_readerreadersworker_sentinelsreadyrrrrNrrrrqs( ,(z3_ExecutorManagerThread.wait_result_broken_or_wakeupcCs~t|tr>|sJ|j|}||jsz|dSn<|j|jd}|durz|j rl|j |j n|j |j dSr)rIintrr}rKr!rrCr=r>r7rL set_resultr?)r rrrPrrrrs   z*_ExecutorManagerThread.process_result_itemcCs|}tp|dup|jSr)r{r_shutdown_thread)r rrrrrs z'_ExecutorManagerThread.is_shutting_downcCs|}|dur d|_d|_d}td}|durHtdd|d|_|jD]\}}|j |~qR|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!r5rCr r7rLrr}r terminater)r rrbper=rPrrrrrs"   z'_ExecutorManagerThread.terminate_brokencCs|}|dur|d|_|jr|i}|jD]\}}|js*|||<q*||_z|jWqLt j yrYqvYqL0qLd|_dS)NTF) r{r_cancel_pending_futuresrCr r7cancelr get_nowaitrr)r rnew_pending_work_itemsr=rPrrrrs   z2_ExecutorManagerThread.flag_executor_shutting_downc Csl|}d}||krh|dkrht||D]8}z|jd|d7}Wq,tjybYq Yq,0q,q dS)Nrr&)get_n_children_aliverangerm put_nowaitrFull)r n_children_to_stopn_sentinels_sentirrrshutdown_workerss   z'_ExecutorManagerThread.shutdown_workerscCsh||j|j|j|jWdn1sB0Y|jD] }|qVdSr) rrmr join_threadrDr#r}rr!r rrrrrs  (z._ExecutorManagerThread.join_executor_internalscCstdd|jDS)Ncss|]}|VqdSr)is_aliverrrr rz>_ExecutorManagerThread.get_n_children_alive..)sumr}rr rrrr sz+_ExecutorManagerThread.get_n_children_alive)rrrrQrrrrrrrrrrrrRrrrGrrss +  & rsc Cshtrtrttdaztd}Wnttfy:YdS0|dkrHdS|dkrTdSd|attdS)NTSC_SEM_NSEMS_MAXz@system provides too few semaphores (%d available, 256 necessary))_system_limits_checked_system_limitedNotImplementedErrorrksysconfAttributeError ValueError) nsems_maxrrr_check_system_limitss rccs&|D]}||r|VqqdS)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)reverserK)iterableelementrrr_chain_from_iterable_of_lists,src@seZdZdZdS)rzy Raised when a process in a ProcessPoolExecutor terminated abruptly while a future was in the running state. N)rrrrQrrrrr8srcs~eZdZdddZddZddZd d Zd d Zd dZe j jj e_ dddfdd Z dddddZ e j j j e _ ZS)ProcessPoolExecutorNrcCsJt|dur6tpd|_tjdkrntt|j|_n8|dkrHtdn tjdkrh|tkrhtdt||_|dur~t }||_ |j j ddd k|_ |durt|std ||_||_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)rFrBrCrDr#T))rrk cpu_count _max_workerssysplatformmin_MAX_WINDOWS_WORKERSrr get_context _mp_contextget_start_method#_safe_to_dynamically_spawn_childrencallable TypeError _initializer _initargs_executor_manager_threadr|r threadingLockrx Semaphorerr _queue_countrrrrwEXTRA_QUEUED_CALLSrAr~ _ignore_epipe SimpleQueuerrrr)r max_workers mp_contextrnro queue_sizerrrr@sZ         zProcessPoolExecutor.__init__cCs<|jdur8|js|t||_|j|jt|j<dSr)rr_launch_processesrsstartrwrr rrr_start_executor_manager_threads   z2ProcessPoolExecutor._start_executor_manager_threadcCs2|jjddrdSt|j}||jkr.|dS)NF)blocking)racquirelenr|r_spawn_process)r process_countrrr_adjust_process_counts   z)ProcessPoolExecutor._adjust_process_countcCs2|jrJdtt|j|jD] }|q dS)NzhProcesses cannot be fork()ed after the thread has started, deadlock in the child processes could result.)rrrr|rr)r r"rrrrs z%ProcessPoolExecutor._launch_processescCs8|jjt|j|j|j|jfd}|||j|j <dS)N)targetr9) rProcessrrr~rrrrr|pidrrrrrsz"ProcessPoolExecutor._spawn_processcOs|j|jrt|j|jr&tdtr2tdt}t||||}||j |j <|j |j |j d7_ |j |jr|||WdS1s0YdS)Nz*cannot schedule new futures after shutdownz6cannot schedule new futures after interpreter shutdownr&)rxrrr RuntimeErrorrrFuturer6rrrrarwrrrr)r r8r9r:fwrrrsubmits"   zProcessPoolExecutor.submitr&)timeoutrWcs:|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.rW)r)rrEmaprr_r[r)r r8rrWrXresultsrGrrrs zProcessPoolExecutor.mapTF)cancel_futurescCs|j0||_d|_|jdur(|jWdn1s<0Y|jdur^|r^|jd|_d|_|jdur|r|j d|_d|_ d|_dSr) rxrrrwrrr!r~rrr|)r rrrrrshutdowns (  zProcessPoolExecutor.shutdown)NNNr)T)rrrrrrrrrrExecutorrQrrrRrrrGrr?s U   r)NN)1rQ __author__rkconcurrent.futuresrrmultiprocessingrmultiprocessing.connectionmultiprocessing.queuesrrry functoolsrrUrr.WeakKeyDictionaryrrrr%_register_atexitrr Exceptionr(r,r3objectr6r<r@rAr[r_rdrrThreadrsrrrrBrokenExecutorrrrrrrrsP*       )