U e5dznã@s”dZdZddlZddlZddlmZddlZddlmZddlZ ddl Zddl m Z ddl Z ddlZddlmZddlZddlZddlZe ¡ZdaGd d „d ƒZd d „Zd ZdZGdd„deƒZGdd„dƒZdd„ZGdd„deƒZ Gdd„deƒZ!Gdd„deƒZ"Gdd„de ƒZ#dd„Z$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/d0„d0ej0ƒZ1e 2e¡dS)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,eZdZdd„Zdd„Zdd„Zdd„Zd S) Ú _ThreadWakeupcCstjdd�\|_|_dS)NF)Zduplex)ÚmpZPipeÚ_readerÚ_writer©Úself©r ú2/usr/lib64/python3.8/concurrent/futures/process.pyÚ__init__Rsz_ThreadWakeup.__init__cCs|j ¡|j ¡dS©N)r Úcloserr r r r rUs z_ThreadWakeup.closecCs|j d¡dS)Nó)r Z send_bytesr r r r ÚwakeupYsz_ThreadWakeup.wakeupcCs|j ¡r|j ¡qdSr)rZpollZ recv_bytesr r r r Úclear\s z_ThreadWakeup.clearN)Ú__name__Ú __module__Ú __qualname__rrrrr r r r rQsrcCs@datt ¡ƒ}|D]\}}| ¡q|D]\}}| ¡q*dS©NT)Ú_global_shutdownÚlistÚ_threads_wakeupsÚitemsrÚjoin)rÚ_Ú thread_wakeupÚtr r r Ú _python_exitas     r éé=c@seZdZdd„Zdd„ZdS)Ú_RemoteTracebackcCs ||_dSr©Útb)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@seZdZdd„Zdd„ZdS)Ú_ExceptionWithTracebackcCs0t t|ƒ||¡}d |¡}||_d||_dS)NÚz """ %s""")Ú tracebackÚformat_exceptionÚtyperÚexcr%)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)rrrrr.r r r r r'sr'cCst|ƒ|_|Sr)r#Ú __cause__)r,r%r r r r-ˆs r-c@seZdZdd„ZdS)Ú _WorkItemcCs||_||_||_||_dSr)ÚfutureÚfnÚargsÚkwargs)r r1r2r3r4r r r r�sz_WorkItem.__init__N©rrrrr r r r r0Œsr0c@seZdZddd„ZdS)Ú _ResultItemNcCs||_||_||_dSr)Úwork_idÚ exceptionÚresult)r r7r8r9r r r r”sz_ResultItem.__init__)NNr5r r r r r6“sr6c@seZdZdd„ZdS)Ú _CallItemcCs||_||_||_||_dSr)r7r2r3r4)r r7r2r3r4r r r ršsz_CallItem.__init__Nr5r r r r r:™sr:cs.eZdZdZd‡fdd„ Z‡fdd„Z‡ZS)Ú _SafeQueuez=Safe Queue set exception to the future object linked to a jobrcs||_tƒj||d�dS)N)Úctx)Úpending_work_itemsÚsuperr)r Úmax_sizer<r=©Ú __class__r r r£sz_SafeQueue.__init__cslt|tƒrZt t|ƒ||j¡}td d |¡¡ƒ|_ |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 ÚeÚobjr%Ú work_itemr@r r rG§s 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)ÚzipÚtupleÚ itertoolsÚislice)Ú chunksizeÚ iterablesÚitÚchunkr r r Ú _get_chunks´s rUcs‡fdd„|DƒS)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 )Ú.0r3©r2r r Ú Æsz"_process_chunk..r )r2rTr rWr Ú_process_chunk½s rYc Cs^z| t|||d�¡Wn@tk rX}z"t||jƒ}| t||d�¡W5d}~XYnXdS)z.Safely send back the given result or exception)r9r8©r8N)Úputr6Ú BaseExceptionr'rC)Ú result_queuer7r9r8rHr,r r r Ú_sendback_resultÉs ÿ  r^c CsÐ|dk rtk r´}z t ||j ƒ}t ||j|d�W5d}~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) ZfullrbÚqueueZEmptyr1Zset_running_or_notify_cancelr[r:r2r3r4)r=Zwork_idsrer7rJr r r Ú_add_call_item_to_queueüs" ýürkc sJd‰‡fdd„}‡‡fdd„}|j} |j} | | g} t||ˆƒdd„ˆ ¡Dƒ} tj | | ¡} d}d}| | krºz|  ¡}d }WqÊtk r¶}zt  t |ƒ||j ¡}W5d}~XYqÊXn| | krÊd }d}|  ¡|�rl|ƒ‰ˆdk röd ˆ_ dˆ_d‰td ƒ}|dk �r td d  |¡›d�ƒ|_| ¡D]\}}|j |¡~�q(|  ¡ˆ ¡D]}| ¡�qR|ƒdSt|tƒ�r¨|ƒ�s„t‚ˆ |¡}| ¡ˆ�sô|ƒdSnL|dk �rô| |jd¡}|dk �rò|j�râ|j |j¡n|j |j¡~~|ƒ‰|ƒ�r@z&ˆdk �rdˆ_|�s&|ƒWdSWntk �r>YnXd‰q2dS)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. NcstpˆdkpˆjSr)rÚ_shutdown_threadr )Úexecutorr r Ú shutting_down@s ÿz/_queue_management_worker..shutting_downc s¬tdd„ˆ ¡Dƒƒ}|}d}||krŠ|dkrŠt||ƒD]6}zˆ d¡|d7}Wq:tk rnYqrYq:Xq:tdd„ˆ ¡Dƒƒ}qˆ ¡ˆ ¡D] }| ¡qšdS)Ncss|]}| ¡VqdSr©Zis_alive©rVÚpr r r Ú FszD_queue_management_worker..shutdown_worker..rr!css|]}| ¡VqdSrrorpr r r rrRs)ÚsumÚvaluesÚrangeZ put_nowaitrrr)Zn_children_aliveZn_children_to_stopZn_sentinels_sentÚirq)reÚ processesr r Úshutdown_workerDs   z1_queue_management_worker..shutdown_workercSsg|] }|j‘qSr )Ú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 connectionÚwaitZrecvr\r)r*r+rCrÚ_brokenrlÚBrokenProcessPoolr#rr/rr1rFZ terminaterBÚintÚAssertionErrorrEr7r8Z set_resultr9r)Zexecutor_referencerwr=Zwork_ids_queuerer]rrnrxZ result_readerZ wakeup_readerZreadersZworker_sentinelsZreadyÚcauseZ is_brokenZ result_itemrHZbper7rJrqr )rermrwr Ú_queue_management_worker"sŠ þ ( ÿ          r€c Csjtrtrttƒ‚dazt d¡}Wnttfk r<YdSX|dkrJdS|dkrVdSd|attƒ‚dS)NTÚSC_SEM_NSEMS_MAXéÿÿÿÿéz@system provides too few semaphores (%d available, 256 necessary))Ú_system_limits_checkedÚ_system_limitedÚNotImplementedErrorrcÚsysconfÚAttributeErrorÚ ValueError)Z nsems_maxr r r Ú_check_system_limitsÆs ÿrŠccs&|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_listsÞsr�c@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|csteZdZddd„Zdd„Zdd„Zd d „Zejjj e_ ejjj e_ dd d œ‡fd d„ Z ddd„Z ejj j e _ ‡Z S)ÚProcessPoolExecutorNr cCstƒ|dkr6t ¡pd|_tjdkrntt|jƒ|_n8|dkrHtdƒ‚n tjdkrh|tkrhtdt›�ƒ‚||_|dkr~t   ¡}||_ |dk rœt |ƒsœt 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)$rŠrcÚ cpu_countÚ _max_workersÚsysÚplatformÚminÚ_MAX_WINDOWS_WORKERSr‰rZ get_contextÚ _mp_contextÚcallableÚ TypeErrorÚ _initializerÚ _initargsÚ_queue_management_threadÚ _processesrlÚ threadingZLockÚ_shutdown_lockr{Ú _queue_countÚ_pending_work_itemsÚEXTRA_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 ròsP  ÿ  ÿÿ  þ  zProcessPoolExecutor.__init__c Csv|jdkrr|jfdd„}| ¡tjtt ||¡|j|j |j |j |j |jfdd�|_d|j_ |j ¡|jt|j<dS)NcSstj d¡| ¡dS)Nz?Executor collected: triggering callback for QueueManager wakeup)rÚutilÚdebugr)rrr r r Ú weakref_cbBs zFProcessPoolExecutor._start_queue_management_thread..weakref_cbZQueueManagerThread)Útargetr3ÚnameT)ršr¤Ú_adjust_process_countrœZThreadr€ÚweakrefÚrefr›rŸr£r¡r¢ZdaemonÚstartr)r r§r r r Ú_start_queue_management_thread=s( ÿ  ú÷  ÿz2ProcessPoolExecutor._start_queue_management_threadcCsPtt|jƒ|jƒD]8}|jjt|j|j|j |j fd�}|  ¡||j|j <qdS)N)r¨r3) ruÚlenr›r�r•ZProcessrir¡r¢r˜r™r­Úpid)r rrqr r r rªXsýþz)ProcessPoolExecutor._adjust_process_countc Os t|ƒdkr|^}}}nV|s&tdƒ‚nHd|krZ| d¡}|^}}ddl}|jdtdd�ntdt|ƒdƒ‚|j�Œ|jr†t|jƒ‚|j r”t d ƒ‚t r t d ƒ‚t   ¡}t||||ƒ}||j|j<|j |j¡|jd7_|j ¡| ¡|W5QR£SQRXdS) NézEdescriptor '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)r¯r—rEÚwarningsÚwarnÚDeprecationWarningr�r{r|rlÚ RuntimeErrorrrZFuturer0rŸržr£r[r¤rr®)r3r4r r2r³ÚfÚwr r r Úsubmitcs<    ÿ ÿ   zProcessPoolExecutor.submitr!)ÚtimeoutrQcs:|dkrtdƒ‚tƒjtt|ƒ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º)r‰r>ÚmaprrYrUr�)r r2rºrQrRZresultsr@r r r»Šs þzProcessPoolExecutor.mapTc CsŠ|j� d|_W5QRX|jr6|j ¡|r6|j ¡d|_|jdk rd|j ¡|r^|j ¡d|_d|_ d|_ |jr†|j ¡d|_dSr) r�rlršr¤rrr¡rZ join_threadr¢r›)r rzr r r Úshutdown§s"      zProcessPoolExecutor.shutdown)NNNr )T)rrrrr®rªr¹rÚExecutorÚ__text_signature__rKr»r¼rLr r r@r rŽñsÿ K $   rŽ)NN)3rKÚ __author__ÚatexitrcZconcurrent.futuresrrjrZmultiprocessingrZmultiprocessing.connectionZmultiprocessing.queuesrrœr«Ú functoolsrrOr‘r)ÚWeakKeyDictionaryrrrr r r”Ú Exceptionr#r'r-Úobjectr0r6r:r;rUrYr^rirkr€r„r…rŠr�ZBrokenExecutorr|r½rŽÚregisterr r r r ÚsV*        )&! P