U :ezn@sdZdZddlZddlZddlmZddlZddlmZddlZ ddl Zddl m Z ddl Z ddlZddlmZddlZddlZddlZeZdaGd d d Zd d Zd ZdZGdddeZGdddZddZGdddeZ GdddeZ!GdddeZ"Gddde Z#ddZ$dd Z%d1d!d"Z&d#d$Z'd%d&Z(d'd(Z)da*da+d)d*Z,d+d,Z-Gd-d.d.ej.Z/Gd/d0d0ej0Z1e2edS)2a- 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)Full)Queue)partialFc@s,eZdZddZddZddZddZd S) _ThreadWakeupcCstjdd\|_|_dS)NF)duplex)mpPipe_reader_writerselfr?/usr/local/python38/lib/python3.8/concurrent/futures/process.py__init__Rsz_ThreadWakeup.__init__cCs|j|jdSN)r closer r rrrrUs z_ThreadWakeup.closecCs|jddS)N)r send_bytesr rrrwakeupYsz_ThreadWakeup.wakeupcCs|jr|jqdSr)r poll recv_bytesr rrrclear\s z_ThreadWakeup.clearN)__name__ __module__ __qualname__rrrrrrrrrQsrcCs@datt}|D]\}}|q|D]\}}|q*dSNT)_global_shutdownlist_threads_wakeupsitemsrjoin)r _ thread_wakeuptrrr _python_exitas     r%=c@seZdZddZddZdS)_RemoteTracebackcCs ||_dSrtb)r r*rrrrzsz_RemoteTraceback.__init__cCs|jSrr)r rrr__str__|sz_RemoteTraceback.__str__N)rrrrr+rrrrr(ysr(c@seZdZddZddZdS)_ExceptionWithTracebackcCs0tt|||}d|}||_d||_dS)Nz """ %s""") tracebackformat_exceptiontyper!excr*)r r1r*rrrrs z _ExceptionWithTraceback.__init__cCst|j|jffSr) _rebuild_excr1r*r rrr __reduce__sz"_ExceptionWithTraceback.__reduce__N)rrrrr3rrrrr,sr,cCst||_|Sr)r( __cause__)r1r*rrrr2s r2c@seZdZddZdS) _WorkItemcCs||_||_||_||_dSr)futurefnargskwargs)r r6r7r8r9rrrrsz_WorkItem.__init__Nrrrrrrrrr5sr5c@seZdZdddZdS) _ResultItemNcCs||_||_||_dSr)work_id exceptionresult)r r<r=r>rrrrsz_ResultItem.__init__)NNr:rrrrr;sr;c@seZdZddZdS) _CallItemcCs||_||_||_||_dSr)r<r7r8r9)r r<r7r8r9rrrrsz_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_itemssuperr)r max_sizerArB __class__rrrsz_SafeQueue.__init__cslt|trZtt|||j}tdd||_ |j |j d}|dk rh|j |nt||dS)Nz """ {}"""r-) isinstancer?r.r/r0 __traceback__r(formatr!r4rBpopr<r6 set_exceptionrC_on_queue_feeder_error)r eobjr* work_itemrErrrLs z!_SafeQueue._on_queue_feeder_error)r)rrr__doc__rrL __classcell__rrrErr@sr@cgs,t|}tt||}|s dS|VqdS)z, Iterates over zip()ed iterables in chunks. N)ziptuple itertoolsislice) chunksize iterablesitchunkrrr _get_chunkss rZcsfdd|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).0r8r7rr sz"_process_chunk..r)r7rYrr\r_process_chunks r^c Cs^z|t|||dWn@tk rX}z"t||j}|t||dW5d}~XYnXdS)z.Safely send back the given result or exception)r>r=r=N)putr; BaseExceptionr,rH) result_queuer<r>r=rMr1rrr_sendback_results   rcc Cs|dk rtk r}z t ||j }t ||j|dW5d}~XYnXt ||j|d~~q)rarLOGGERcriticalgetr`osgetpidr7r8r9r,rHrcr<) call_queuerb initializerinitargs call_itemrrMr1rrr_process_workers$    "rqcCsv|r dSz|jdd}Wntjk r4YdSX||}|jrh|jt||j|j |j ddq||=qqdS)aMFills call_queue with _WorkItems from pending_work_items. This function never blocks. Args: pending_work_items: A dict mapping work ids to _WorkItems e.g. {5: <_WorkItem...>, 6: <_WorkItem...>, ...} work_ids: A queue.Queue of work ids e.g. Queue([5, 6, ...]). Work ids are consumed and the corresponding _WorkItems from pending_work_items are transformed into _CallItems and put in call_queue. call_queue: A multiprocessing.Queue that will be filled with _CallItems derived from _WorkItems. NFreT) fullriqueueEmptyr6set_running_or_notify_cancelr`r?r7r8r9)rBwork_idsrlr<rOrrr_add_call_item_to_queues" rwc s>dfdd}fdd}|j} |j} | | g} t||ddD} tj| | } d}d}| | krz| }d }Wqtk r}zt t |||j }W5d}~XYqXn| | krd }d}| |rl|dk rd _ d_dtd }|dk r td d |d|_|D]\}}|j|~q(| D]}|qR|dSt|tr|}|s|dSnL|dk r||jd}|dk r|jr|j|jn|j|j~~||r4z&dk rd_|s|WdSWntk r2YnXdq2dS)a,Manages the communication between this process and the worker processes. This function is run in a local thread. Args: executor_reference: A weakref.ref to the ProcessPoolExecutor that owns this thread. Used to determine if the ProcessPoolExecutor has been garbage collected and that this function can exit. process: A list of the ctx.Process instances used as workers. pending_work_items: A dict mapping work ids to _WorkItems e.g. {5: <_WorkItem...>, 6: <_WorkItem...>, ...} work_ids_queue: A queue.Queue of work ids e.g. Queue([5, 6, ...]). call_queue: A ctx.Queue that will be filled with _CallItems derived from _WorkItems for processing by the process workers. result_queue: A ctx.SimpleQueue of _ResultItems generated by the process workers. thread_wakeup: A _ThreadWakeup to allow waking up the queue_manager_thread from the main Thread and avoid deadlocks caused by permanently locked queues. NcstpdkpjSr)r_shutdown_threadr)executorrr shutting_down@s z/_queue_management_worker..shutting_downc stddD}|}d}||kr|dkrt||D]6}zd|d7}Wq:tk rnYqrYq:Xq:tddD}qD] }|qdS)Ncss|]}|VqdSris_aliver[prrr FszD_queue_management_worker..shutdown_worker..rr&css|]}|VqdSrr{r}rrrrRs)sumvaluesrange put_nowaitrrr!)n_children_aliven_children_to_stopn_sentinels_sentir~)rl processesrrshutdown_workerDs   z1_queue_management_worker..shutdown_workercSsg|] }|jqSr)sentinelr}rrrr]isz,_queue_management_worker..TFzKA child process terminated abruptly, the process pool is not usable anymorez^A process in the process pool was terminated abruptly while the future was running or pending.z ''' r-z''')r rwrr connectionwaitrecvrar.r/r0rHr_brokenrxBrokenProcessPoolr(r!r4r r6rK terminaterGintrJr<r= set_resultr>r)executor_referencerrBwork_ids_queuerlrbr#rzr result_reader wakeup_readerreadersworker_sentinelsreadycause is_broken result_itemrMbper<rOr~r)rlryrr_queue_management_worker"s  (          rc Csjtrtrttdaztd}Wnttfk r<YdSX|dkrJdS|dkrVdSd|attdS)NTSC_SEM_NSEMS_MAXz@system provides too few semaphores (%d available, 256 necessary))_system_limits_checked_system_limitedNotImplementedErrorrjsysconfAttributeError 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)reverserJ)iterableelementrrr_chain_from_iterable_of_listssrc@seZdZdZdS)rzy Raised when a process in a ProcessPoolExecutor terminated abruptly while a future was in the running state. N)rrrrPrrrrrsrcsteZdZdddZddZddZd d Zejjj e_ ejjj e_ dd d fd d Z dddZ ejj j e _ Z S)ProcessPoolExecutorNrcCst|dkr6tpd|_tjdkrntt|j|_n8|dkrHtdn tjdkrh|tkrhtdt||_|dkr~t }||_ |dk rt |st d||_||_d|_i|_d|_t|_d|_d|_i|_|jt}t||j |jd |_d |j_||_t |_!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 <= zinitializer must be a callableF)rDrArBT)$rrj cpu_count _max_workerssysplatformmin_MAX_WINDOWS_WORKERSrr get_context _mp_contextcallable TypeError _initializer _initargs_queue_management_thread _processesrx threadingLock_shutdown_lockr _queue_count_pending_work_itemsEXTRA_QUEUED_CALLSr@ _call_queue _ignore_epipe SimpleQueue _result_queuersr _work_idsr_queue_management_thread_wakeup)r max_workers mp_contextrmrn queue_sizerrrrsP        zProcessPoolExecutor.__init__c Csv|jdkrr|jfdd}|tjtt|||j|j |j |j |j |jfdd|_d|j_ |j|jt|j<dS)NcSstjd|dS)Nz?Executor collected: triggering callback for QueueManager wakeup)rutildebugr)r"r#rrr weakref_cbBs zFProcessPoolExecutor._start_queue_management_thread..weakref_cbQueueManagerThread)targetr8nameT)rr_adjust_process_countrThreadrweakrefrefrrrrrdaemonstartr)r rrrr_start_queue_management_thread=s(     z2ProcessPoolExecutor._start_queue_management_threadcCsPtt|j|jD]8}|jjt|j|j|j |j fd}| ||j|j <qdS)N)rr8) rlenrrrProcessrqrrrrrpid)r r"r~rrrrXsz)ProcessPoolExecutor._adjust_process_countc Os t|dkr|^}}}nV|s&tdnHd|krZ|d}|^}}ddl}|jdtddntdt|d|j|jrt|j|j rt d t rt d t }t||||}||j|j<|j|j|jd7_|j||W5QRSQRXdS) NzEdescriptor 'submit' of 'ProcessPoolExecutor' object needs an argumentr7rz.Passing 'fn' as keyword argument is deprecated) stacklevelz6submit expected at least 1 positional argument, got %dr&z*cannot schedule new futures after shutdownz6cannot schedule new futures after interpreter shutdown)rrrJwarningswarnDeprecationWarningrrrrx RuntimeErrorrrFuturer5rrrr`rrr)r8r9r r7rfwrrrsubmitcs<        zProcessPoolExecutor.submitr&)timeoutrVcs:|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.rV)r)rrCmaprr^rZr)r r7rrVrWresultsrErrrs zProcessPoolExecutor.mapTc Cs|j d|_W5QRX|jr6|j|r6|jd|_|jdk rd|j|r^|jd|_d|_ d|_ |jr|jd|_dSr) rrxrrrr!rr join_threadrr)r rrrrshutdowns"      zProcessPoolExecutor.shutdown)NNNr)T)rrrrrrrrExecutor__text_signature__rPrrrQrrrErrs K $   r)NN)3rP __author__atexitrjconcurrent.futuresrrsrmultiprocessingrmultiprocessing.connectionmultiprocessing.queuesrrr functoolsrrTrr.WeakKeyDictionaryrrrr%rr Exceptionr(r,r2objectr5r;r?r@rZr^rcrqrwrrrrrBrokenExecutorrrrregisterrrrrsV*        )&! P