Your IP : 18.223.134.71
U
e5dzn�@s�dZdZddlZddlZddlmZddlZddlmZddlZ ddl
ZddlmZddl
Z
ddlZddlmZddlZddlZddlZe��ZdaGd d
�d
�Zdd�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
rrr
rUs
z_ThreadWakeup.closecCs|j�d�dS)N�)r Z
send_bytesr
rrr
�wakeupYsz_ThreadWakeup.wakeupcCs|j��r|j��qdSr)rZpollZ
recv_bytesr
rrr
�clear\s
z_ThreadWakeup.clearN)�__name__�
__module__�__qualname__rrrrrrrr
rQsrcCs@datt���}|D]\}}|��q|D]\}}|��q*dS�NT)�_global_shutdown�list�_threads_wakeups�itemsr�join)r�_�
thread_wakeup�trrr
�_python_exitas
r ��=c@seZdZdd�Zdd�ZdS)�_RemoteTracebackcCs
||_dSr��tb)rr%rrr
rzsz_RemoteTraceback.__init__cCs|jSrr$r
rrr
�__str__|sz_RemoteTraceback.__str__N)rrrrr&rrrr
r#ysr#c@seZdZdd�Zdd�ZdS)�_ExceptionWithTracebackcCs0t�t|�||�}d�|�}||_d||_dS)N�z
"""
%s""")� traceback�format_exception�typer�excr%)rr,r%rrr
r�s
z _ExceptionWithTraceback.__init__cCst|j|jffSr)�_rebuild_excr,r%r
rrr
�
__reduce__�sz"_ExceptionWithTraceback.__reduce__N)rrrrr.rrrr
r'sr'cCst|�|_|Sr)r#� __cause__)r,r%rrr
r-�s
r-c@seZdZdd�ZdS)� _WorkItemcCs||_||_||_||_dSr)�future�fn�args�kwargs)rr1r2r3r4rrr
r�sz_WorkItem.__init__N�rrrrrrrr
r0�sr0c@seZdZddd�ZdS)�_ResultItemNcCs||_||_||_dSr)�work_id� exception�result)rr7r8r9rrr
r�sz_ResultItem.__init__)NNr5rrrr
r6�sr6c@seZdZdd�ZdS)� _CallItemcCs||_||_||_||_dSr)r7r2r3r4)rr7r2r3r4rrr
r�sz_CallItem.__init__Nr5rrrr
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__rr
r�sz_SafeQueue.__init__cslt|t�rZt�t|�||j�}td�d�|���|_ |j
�|jd�}|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@rr
rG�s
z!_SafeQueue._on_queue_feeder_error)r)rrr�__doc__rrG�
__classcell__rrr@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�chunkrrr
�_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|]}�|��qSrr)�.0r3�r2rr
�
<listcomp>�sz"_process_chunk.<locals>.<listcomp>r)r2rTrrWr
�_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,rrr
�_sendback_result�s
�r^c
Cs�|dk r<z||�Wn&tk
r:tjjddd�YdSX|jdd�}|dkrb|�t���dSz|j|j |j
�}Wn>tk
r�}z t||j�}t
||j|d�W5d}~XYnXt
||j|d�~~q<dS)a�Evaluates 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_info��blockrZ)r9)r\rZLOGGERZcritical�getr[�os�getpidr2r3r4r'rCr^r7)�
call_queuer]�initializer�initargsZ call_item�rrHr,rrr
�_process_worker�s$
"ricCsv|��rdSz|jdd�}Wntjk
r4YdSX||}|j��rh|jt||j|j |j
�dd�q||=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.
NFr`T)Zfullrb�queueZEmptyr1Zset_running_or_notify_cancelr[r:r2r3r4)r=Zwork_idsrer7rJrrr
�_add_call_item_to_queue�s"
��rkc
s>d��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 tdd
�|��d��|_|��D]\}}|j�|�~�q(|�����D]}|���qR|�dSt|t��r���|�}|����s�|�dSnL|dk �r�|�|jd�}|dk �r�|j�r�|j�|j�n|j�|j�~~|��|��r4z&�dk �rd�_|�s|�WdSWntk
�r2YnXd�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)�executorrr
�
shutting_down@s�z/_queue_management_worker.<locals>.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�prrr
� <genexpr>FszD_queue_management_worker.<locals>.shutdown_worker.<locals>.<genexpr>rr!css|]}|��VqdSrrorprrr
rrRs)�sum�values�rangeZ
put_nowaitrrr)Zn_children_aliveZn_children_to_stopZn_sentinels_sent�irq)re� processesrr
�shutdown_workerDs
z1_queue_management_worker.<locals>.shutdown_workercSsg|]
}|j�qSr)�sentinelrprrr
rXisz,_queue_management_worker.<locals>.<listcomp>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�intrEr7r8Z
set_resultr9r)Zexecutor_referencerwr=Zwork_ids_queuerer]rrnrxZ
result_readerZ
wakeup_readerZreadersZworker_sentinelsZready�causeZ is_brokenZresult_itemrHZbper7rJrqr)rermrwr
�_queue_management_worker"s�� (
�
rc 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_maxrrr
�_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)�iterableZelementrrr
�_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)rrrrKrrrr
r|�sr|csteZdZddd�Zdd�Zdd�Zd d
�Zejjj e_ ejjj
e_
ddd��fd
d�
Zddd�Zejjj
e_
�Z
S)�ProcessPoolExecutorNrcCst�|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�rZget_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_epipeZSimpleQueue�
_result_queuerjr� _work_idsr�_queue_management_thread_wakeup)rZmax_workersZ
mp_contextrfrgZ
queue_sizerrr
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)rrrrr
�
weakref_cbBszFProcessPoolExecutor._start_queue_management_thread.<locals>.weakref_cbZQueueManagerThread)�targetr3�nameT)r�r��_adjust_process_countr�ZThreadr�weakref�refr�r�r�r�r�Zdaemon�startr)rr�rrr
�_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)rrrqrrr
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 ��tr�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�)r3r4rr2r��f�wrrr
�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�)rr2r�rQrRZresultsr@rr
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�rZjoin_threadr�r�)rrzrrr
�shutdown�s"
zProcessPoolExecutor.shutdown)NNNr)T)rrrrr�r�r�r�Executor�__text_signature__rKr�r�rLrrr@r
r��s�
K$
r�)NN)3rK�
__author__�atexitrcZconcurrent.futuresrrjrZmultiprocessingrZmultiprocessing.connectionZmultiprocessing.queuesrr�r�� functoolsrrOr�r)�WeakKeyDictionaryrrrr r�r�� Exceptionr#r'r-�objectr0r6r:r;rUrYr^rirkrr�r�r�r�ZBrokenExecutorr|r�r��registerrrrr
�<module>sV*
)&!P
?>