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 ([email protected])�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