U e5dzn@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)Zduplex)mpZPipe_reader_writerselfr 2/usr/lib64/python3.8/concurrent/futures/process.py__init__Rsz_ThreadWakeup.__init__cCs|j|jdSN)r closerr r r r rUs z_ThreadWakeup.closecCs|jddS)N)r Z send_bytesr r r r wakeupYsz_ThreadWakeup.wakeupcCs|jr|jqdSr)rZpollZ recv_bytesr r r r clear\s z_ThreadWakeup.clearN)__name__ __module__ __qualname__rrrrr r r r rQsrcCs@datt}|D]\}}|q|D]\}}|q*dSNT)_global_shutdownlist_threads_wakeupsitemsrjoin)r_ thread_wakeuptr r r _python_exitas     r =c@seZdZddZddZdS)_RemoteTracebackcCs ||_dSrtb)r r%r r r rzsz_RemoteTraceback.__init__cCs|jSrr$r r r r __str__|sz_RemoteTraceback.__str__N)rrrrr&r r r r r#ysr#c@seZdZddZddZdS)_ExceptionWithTracebackcCs0tt|||}d|}||_d||_dS)Nz """ %s""") tracebackformat_exceptiontyperexcr%)r r,r%r r r rs z _ExceptionWithTraceback.__init__cCst|j|jffSr) _rebuild_excr,r%r r r r __reduce__sz"_ExceptionWithTraceback.__reduce__N)rrrrr.r r r r r'sr'cCst||_|Sr)r# __cause__)r,r%r r r r-s r-c@seZdZddZdS) _WorkItemcCs||_||_||_||_dSr)futurefnargskwargs)r r1r2r3r4r r r rsz_WorkItem.__init__Nrrrrr r r r r0sr0c@seZdZdddZdS) _ResultItemNcCs||_||_||_dSr)work_id exceptionresult)r r7r8r9r r r rsz_ResultItem.__init__)NNr5r r r r r6sr6c@seZdZddZdS) _CallItemcCs||_||_||_||_dSr)r7r2r3r4)r r7r2r3r4r r r rsz_CallItem.__init__Nr5r r r r r: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_sizer<r= __class__r r rsz_SafeQueue.__init__cslt|trZtt|||j}tdd||_ |j |j d}|dk rh|j |nt||dS)Nz """ {}"""r() isinstancer:r)r*r+ __traceback__r#formatrr/r=popr7r1 set_exceptionr>_on_queue_feeder_error)r eobjr% work_itemr@r r rGs z!_SafeQueue._on_queue_feeder_error)r)rrr__doc__rrG __classcell__r r r@r r;sr;cgs,t|}tt||}|s dS|VqdS)z, Iterates over zip()ed iterables in chunks. N)ziptuple itertoolsislice) chunksize iterablesitchunkr r r _get_chunkss rUcsfdd|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 ).0r3r2r r sz"_process_chunk..r )r2rTr rWr _process_chunks rYc Cs^z|t|||dWn@tk rX}z"t||j}|t||dW5d}~XYnXdS)z.Safely send back the given result or exception)r9r8r8N)putr6 BaseExceptionr'rC) result_queuer7r9r8rHr,r r r _sendback_results   r^c Cs|dk rtk r}z t ||j }t ||j|dW5d}~XYnXt ||j|d~~q, 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. NFr`T) ZfullrbqueueZEmptyr1Zset_running_or_notify_cancelr[r:r2r3r4)r=Zwork_idsrer7rJr r r _add_call_item_to_queues" rkc 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 )executorr r 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|]}|VqdSrZis_aliverVpr r r FszD_queue_management_worker..shutdown_worker..rr!css|]}|VqdSrrorpr r r rrRs)sumvaluesrangeZ put_nowaitrrr)Zn_children_aliveZn_children_to_stopZn_sentinels_sentirq)re processesr r shutdown_workerDs   z1_queue_management_worker..shutdown_workercSsg|] }|jqSr )sentinelrpr r r rXisz,_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''')rrkrtrZ connectionwaitZrecvr\r)r*r+rCr_brokenrlBrokenProcessPoolr#rr/rr1rFZ terminaterBintrEr7r8Z set_resultr9r)Zexecutor_referencerwr=Zwork_ids_queuerer]rrnrxZ result_readerZ wakeup_readerZreadersZworker_sentinelsZreadycauseZ is_brokenZ result_itemrHZbper7rJrqr )rermrwr _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_limitedNotImplementedErrorrcsysconfAttributeError ValueError)Z nsems_maxr r r _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)reverserE)iterableZelementr r r _chain_from_iterable_of_listssrc@seZdZdZdS)r|zy Raised when a process in a ProcessPoolExecutor terminated abruptly while a future was in the running state. N)rrrrKr r r r r|sr|csteZdZdddZddZddZd d Zejjj e_ ejjj e_ dd d fd d Z dddZ ejj j e _ Z S)ProcessPoolExecutorNr cCst|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!Zwin32rz"max_workers must be greater than 0zmax_workers must be <= zinitializer must be a callableF)r?r<r=T)$rrc cpu_count _max_workerssysplatformmin_MAX_WINDOWS_WORKERSrrZ get_context _mp_contextcallable TypeError _initializer _initargs_queue_management_thread _processesrl threadingZLock_shutdown_lockr{ _queue_count_pending_work_itemsEXTRA_QUEUED_CALLSr; _call_queueZ _ignore_epipeZ SimpleQueue _result_queuerjr _work_idsr_queue_management_thread_wakeup)r Z max_workersZ mp_contextrfrgZ queue_sizer r r rsP        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)rrr r r weakref_cbBs zFProcessPoolExecutor._start_queue_management_thread..weakref_cbZQueueManagerThread)targetr3nameT)rr_adjust_process_countrZThreadrweakrefrefrrrrrZdaemonstartr)r rr r r _start_queue_management_thread=s(     z2ProcessPoolExecutor._start_queue_management_threadcCsPtt|j|jD]8}|jjt|j|j|j |j fd}| ||j|j <qdS)N)rr3) rulenrrrZProcessrirrrrrpid)r rrqr r r rXsz)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 argumentr2rz.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)rrrEwarningswarnDeprecationWarningrr{r|rl RuntimeErrorrrZFuturer0rrrr[rrr)r3r4r r2rfwr r r submitcs<        zProcessPoolExecutor.submitr!)timeoutrQcs:|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.rQ)r)rr>maprrYrUr)r r2rrQrRZresultsr@r r rs zProcessPoolExecutor.mapTc Cs|j d|_W5QRX|jr6|j|r6|jd|_|jdk rd|j|r^|jd|_d|_ d|_ |jr|jd|_dSr) rrlrrrrrrZ join_threadrr)r rzr r r shutdowns"      zProcessPoolExecutor.shutdown)NNNr )T)rrrrrrrrExecutor__text_signature__rKrrrLr r r@r rs K $   r)NN)3rK __author__atexitrcZconcurrent.futuresrrjrZmultiprocessingrZmultiprocessing.connectionZmultiprocessing.queuesrrr functoolsrrOrr)WeakKeyDictionaryrrrr rr Exceptionr#r'r-objectr0r6r:r;rUrYr^rirkrrrrrZBrokenExecutorr|rrregisterr r r r sV*        )&! P