/home/lnzliplg/public_html/futures.zip
PK�j�\��x�E5E5(__pycache__/process.cpython-38.opt-2.pycnu�[���U

e5dzn�@s�dZddlZddlZddlmZddlZddlmZddlZddl	Zddl
mZddlZddl
Z
ddlmZddlZddlZddlZe
��ZdaGdd	�d	�Zd
d�ZdZd
ZGdd�de�ZGdd�d�Zdd�ZGdd�de�ZGdd�de�Z Gdd�de�Z!Gdd�de�Z"dd�Z#dd�Z$d0d 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.d/�d/ej/�Z0e�1e�dS)1z"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)rr%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%)rr,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)rr1r2r3r4rrr
r�sz_WorkItem.__init__N�rrrrrrrr
r0�sr0c@seZdZddd�ZdS)�_ResultItemNcCs||_||_||_dSr)�work_id�	exception�result)rr7r8r9rrr
r�sz_ResultItem.__init__)NNr5rrrr
r6�sr6c@seZdZdd�ZdS)�	_CallItemcCs||_||_||_||_dSr)r7r2r3r4)rr7r2r3r4rrr
r�sz_CallItem.__init__Nr5rrrr
r:�sr:cs*eZdZd�fdd�	Z�fdd�Z�ZS)�
_SafeQueuercs||_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)rrrrrG�
__classcell__rrr@r
r;�sr;cgs,t|�}tt�||��}|s dS|VqdSr)�zip�tuple�	itertools�islice)�	chunksize�	iterables�it�chunkrrr
�_get_chunks�s
rTcs�fdd�|D�S)Ncsg|]}�|��qSrr)�.0r3�r2rr
�
<listcomp>�sz"_process_chunk.<locals>.<listcomp>r)r2rSrrVr
�_process_chunk�s	rXc
Cs^z|�t|||d��Wn@tk
rX}z"t||j�}|�t||d��W5d}~XYnXdS)N)r9r8�r8)�putr6�
BaseExceptionr'rC)�result_queuer7r9r8rHr,rrr
�_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)NzException in initializer:T)�exc_info��blockrY)r9)r[rZLOGGERZcritical�getrZ�os�getpidr2r3r4r'rCr]r7)�
call_queuer\�initializer�initargsZ	call_item�rrHr,rrr
�_process_worker�s$
"rhcCsv|��rdSz|jdd�}Wntjk
r4YdSX||}|j��rh|jt||j|j	|j
�dd�q||=qqdS)NFr_T)Zfullra�queueZEmptyr1Zset_running_or_notify_cancelrZr:r2r3r4)r=Zwork_idsrdr7rJrrr
�_add_call_item_to_queue�s"
��rjc
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)Ncstp�dkp�jSr)r�_shutdown_threadr)�executorrr
�
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�rU�prrr
�	<genexpr>FszD_queue_management_worker.<locals>.shutdown_worker.<locals>.<genexpr>rr!css|]}|��VqdSrrnrorrr
rqRs)�sum�values�rangeZ
put_nowaitrrr)Zn_children_aliveZn_children_to_stopZn_sentinels_sent�irp)rd�	processesrr
�shutdown_workerDs
z1_queue_management_worker.<locals>.shutdown_workercSsg|]
}|j�qSr)�sentinelrorrr
rWisz,_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''')rrjrsrZ
connection�waitZrecvr[r)r*r+rCr�_brokenrk�BrokenProcessPoolr#rr/rr1rFZ	terminaterB�intrEr7r8Z
set_resultr9r)Zexecutor_referencervr=Zwork_ids_queuerdr\rrmrwZ
result_readerZ
wakeup_readerZreadersZworker_sentinelsZready�causeZ	is_brokenZresult_itemrHZbper7rJrpr)rdrlrvr
�_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�NotImplementedErrorrb�sysconf�AttributeError�
ValueError)Z	nsems_maxrrr
�_check_system_limits�s �r�ccs&|D]}|��|r|��VqqdSr)�reverserE)�iterableZelementrrr
�_chain_from_iterable_of_lists�sr�c@seZdZdS)r{N)rrrrrrr
r{�sr{csteZdZddd�Zdd�Zdd�Zd	d
�Zejjj	e_	ejjj
e_
ddd��fd
d�
Zddd�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)
Nr!Zwin32rz"max_workers must be greater than 0zmax_workers must be <= zinitializer must be a callableF)r?r<r=T)$r�rb�	cpu_count�_max_workers�sys�platform�min�_MAX_WINDOWS_WORKERSr�rZget_context�_mp_context�callable�	TypeError�_initializer�	_initargs�_queue_management_thread�
_processesrk�	threadingZLock�_shutdown_lockrz�_queue_count�_pending_work_items�EXTRA_QUEUED_CALLSr;�_call_queueZ
_ignore_epipeZSimpleQueue�
_result_queuerir�	_work_idsr�_queue_management_thread_wakeup)rZmax_workersZ
mp_contextrerfZ
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.<locals>.weakref_cbZQueueManagerThread)�targetr3�nameT)r�r��_adjust_process_countr�ZThreadr~�weakref�refr�r�r�r�r�Zdaemon�startr)rr�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)
rt�lenr�r�r�ZProcessrhr�r�r�r�r��pid)rrrpr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	��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�rzr{rk�RuntimeErrorrrZFuturer0r�r�r�rZr�rr�)r3r4rr2r��f�wrrr
�submitcs<

�
�

zProcessPoolExecutor.submitr!)�timeoutrPcs:|dkrtd��t�jtt|�t|d|i�|d�}t|�S)Nr!zchunksize must be >= 1.rP)r�)r�r>�maprrXrTr�)rr2r�rPrQZresultsr@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�rkr�r�rrr�rZjoin_threadr�r�)rryrrr
�shutdown�s"





zProcessPoolExecutor.shutdown)NNNr)T)rrrrr�r�r�r�Executor�__text_signature__�__doc__r�r�rKrrr@r
r��s�
K$
r�)NN)2�
__author__�atexitrbZconcurrent.futuresrrirZmultiprocessingrZmultiprocessing.connectionZmultiprocessing.queuesrr�r��	functoolsrrNr�r)�WeakKeyDictionaryrrrr r�r��	Exceptionr#r'r-�objectr0r6r:r;rTrXr]rhrjr~r�r�r�r�ZBrokenExecutorr{r�r��registerrrrr
�<module>.sT
		

)&!PPK�j�\�����'__pycache__/thread.cpython-38.opt-2.pycnu�[���U

e5d@"�@s�dZddlZddlmZddlZddlZddlZddlZddlZe�	�Z
dadd�Ze�
e�Gdd�de�Zd	d
�ZGdd�dej�ZGd
d�dej�ZdS)z"Brian Quinlan (brian@sweetapp.com)�N)�_baseFcCsBdatt���}|D]\}}|�d�q|D]\}}|��q,dS�NT)�	_shutdown�list�_threads_queues�items�put�join)r�t�q�r�1/usr/lib64/python3.8/concurrent/futures/thread.py�_python_exit!src@seZdZdd�Zdd�ZdS)�	_WorkItemcCs||_||_||_||_dS�N)�future�fn�args�kwargs)�selfrrrrrrr
�__init__.sz_WorkItem.__init__c
Csf|j��sdSz|j|j|j�}Wn2tk
rT}z|j�|�d}W5d}~XYnX|j�|�dSr)rZset_running_or_notify_cancelrrr�
BaseException�
set_exceptionZ
set_result)r�result�excrrr
�run4s
z
_WorkItem.runN)�__name__�
__module__�__qualname__rrrrrr
r-srcCs�|dk	rRz||�Wn<tk
rPtjjddd�|�}|dk	rJ|��YdSXzx|jdd�}|dk	r�|��~|�}|dk	r�|j��~qT|�}t	s�|dks�|j	r�|dk	r�d|_	|�
d�WdS~qTWn$tk
r�tjjddd�YnXdS)NzException in initializer:T)�exc_info)�blockzException in worker)rrZLOGGERZcritical�_initializer_failed�getr�_idle_semaphore�releaserr)Zexecutor_referenceZ
work_queue�initializer�initargsZexecutor�	work_itemrrr
�_workerBs8

r(c@seZdZdS)�BrokenThreadPoolN)rrrrrrr
r)msr)c@sfeZdZe��jZddd�Zdd�Ze	j
jje_e	j
jje_dd	�Z
d
d�Zdd
d�Ze	j
jje_dS)�ThreadPoolExecutorN�rcCs�|dkrtdt��pdd�}|dkr.td��|dk	rFt|�sFtd��||_t��|_	t
�d�|_t
�|_d|_d|_t
��|_|p�d|��|_||_||_dS)	N� ��rz"max_workers must be greater than 0zinitializer must be a callableFzThreadPoolExecutor-%d)�min�os�	cpu_count�
ValueError�callable�	TypeError�_max_workers�queueZSimpleQueue�_work_queue�	threadingZ	Semaphorer#�set�_threads�_brokenrZLock�_shutdown_lock�_counter�_thread_name_prefix�_initializer�	_initargs)rZmax_workersZthread_name_prefixr%r&rrr
rxs$


�zThreadPoolExecutor.__init__c
Os�t|�dkr|^}}}nV|s&td��nHd|krZ|�d�}|^}}ddl}|jdtdd�ntdt|�d��|j�f|jr�t|j��|j	r�t
d	��t	r�t
d
��t��}t
||||�}|j�|�|��|W5QR�SQRXdS)N�zDdescriptor 'submit' of 'ThreadPoolExecutor' object needs an argumentrrz.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)�lenr4�pop�warnings�warn�DeprecationWarningr<r;r)r�RuntimeErrorrZFuturerr7r�_adjust_thread_count)rrrrrE�f�wrrr
�submit�s6

�
�
zThreadPoolExecutor.submitcCs�|jjdd�rdS|jfdd�}t|j�}||jkr�d|jp>||f}tj|t	t
�||�|j|j|j
fd�}d|_|��|j�|�|jt|<dS)Nr)ZtimeoutcSs|�d�dSr)r)�_rrrr
�
weakref_cb�sz;ThreadPoolExecutor._adjust_thread_count.<locals>.weakref_cbz%s_%d)�name�targetrT)r#�acquirer7rCr:r5r>r8ZThreadr(�weakref�refr?r@Zdaemon�start�addr)rrNZnum_threadsZthread_namer
rrr
rI�s&


�
��z'ThreadPoolExecutor._adjust_thread_countc	Csb|j�Rd|_z|j��}Wntjk
r6YqTYnX|dk	r|j�t|j��qW5QRXdS)NzBA thread initializer failed, the thread pool is not usable anymore)	r<r;r7Z
get_nowaitr6ZEmptyrrr))rr'rrr
r!�s
z&ThreadPoolExecutor._initializer_failedTc	Cs@|j�d|_|j�d�W5QRX|r<|jD]}|��q.dSr)r<rr7rr:r	)r�waitr
rrr
�shutdown�s
zThreadPoolExecutor.shutdown)Nr+Nr)T)rrr�	itertools�count�__next__r=rrLr�Executor�__text_signature__�__doc__rIr!rWrrrr
r*ss
�
& 
r*)�
__author__�atexitZconcurrent.futuresrrXr6r8rRr0�WeakKeyDictionaryrrr�register�objectrr(ZBrokenExecutorr)r[r*rrrr
�<module>s	
+PK�j�\�Da�NONO"__pycache__/process.cpython-38.pycnu�[���U

e5dzn�@s�dZdZddlZddlZddlmZddlZddlmZddlZ	ddl
ZddlmZddl
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
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)rr%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%)rr,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)rr1r2r3r4rrr
r�sz_WorkItem.__init__N�rrrrrrrr
r0�sr0c@seZdZddd�ZdS)�_ResultItemNcCs||_||_||_dSr)�work_id�	exception�result)rr7r8r9rrr
r�sz_ResultItem.__init__)NNr5rrrr
r6�sr6c@seZdZdd�ZdS)�	_CallItemcCs||_||_||_||_dSr)r7r2r3r4)rr7r2r3r4r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
�
<listcomp>�sz"_process_chunk.<locals>.<listcomp>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	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,rrr
�_process_worker�s$
"ricCsv|��rdSz|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_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.<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�prrr
�	<genexpr>FszD_queue_management_worker.<locals>.shutdown_worker.<locals>.<genexpr>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.<locals>.shutdown_workercSsg|]
}|j�qSr)�sentinelrprrr
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�int�AssertionErrorrEr7r8Z
set_resultr9r)Zexecutor_referencerwr=Zwork_ids_queuerer]rrnrxZ
result_readerZ
wakeup_readerZreadersZworker_sentinelsZready�causeZ	is_brokenZresult_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_
ddd��fd
d�
Zddd�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�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_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.<locals>.weakref_cbZQueueManagerThread)�targetr3�nameT)r�r��_adjust_process_countr�ZThreadr��weakref�refr�r�r�r�r�Zdaemon�startr)rr�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)rrrqr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	��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�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�)rr2r�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�rZjoin_threadr�r�)rrzr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
�<module>sV*
		

)&!PPK�j�\(��0O0O(__pycache__/process.cpython-38.opt-1.pycnu�[���U

e5dzn�@s�dZdZddlZddlZddlmZddlZddlmZddlZ	ddl
ZddlmZddl
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
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)rr%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%)rr,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)rr1r2r3r4rrr
r�sz_WorkItem.__init__N�rrrrrrrr
r0�sr0c@seZdZddd�ZdS)�_ResultItemNcCs||_||_||_dSr)�work_id�	exception�result)rr7r8r9rrr
r�sz_ResultItem.__init__)NNr5rrrr
r6�sr6c@seZdZdd�ZdS)�	_CallItemcCs||_||_||_||_dSr)r7r2r3r4)rr7r2r3r4r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
�
<listcomp>�sz"_process_chunk.<locals>.<listcomp>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	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,rrr
�_process_worker�s$
"ricCsv|��rdSz|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_idsrer7rJrrr
�_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 tdd
�|��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)�executorrr
�
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�prrr
�	<genexpr>FszD_queue_management_worker.<locals>.shutdown_worker.<locals>.<genexpr>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.<locals>.shutdown_workercSsg|]
}|j�qSr)�sentinelrprrr
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_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_
ddd��fd
d�
Zddd�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�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_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.<locals>.weakref_cbZQueueManagerThread)�targetr3�nameT)r�r��_adjust_process_countr�ZThreadr�weakref�refr�r�r�r�r�Zdaemon�startr)rr�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)rrrqr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	��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�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�)rr2r�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�rZjoin_threadr�r�)rrzr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^rirkrr�r�r�r�ZBrokenExecutorr|r�r��registerrrrr
�<module>sV*
		

)&!PPK�j�\$��ڶU�U __pycache__/_base.cpython-38.pycnu�[���U

e5dY�
@spdZddlZddlZddlZddlZdZdZdZdZdZ	dZ
d	Zd
ZdZ
e	e
eee
gZe	de
d
edede
diZe�d�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd �d e�ZGd!d"�d"e�Zd#d$�Zd%d&�Zd3d'd(�Ze� d)d*�Z!defd+d,�Z"Gd-d.�d.e�Z#Gd/d0�d0e�Z$Gd1d2�d2e%�Z&dS)4z"Brian Quinlan (brian@sweetapp.com)�N�FIRST_COMPLETED�FIRST_EXCEPTION�
ALL_COMPLETED�
_AS_COMPLETED�PENDING�RUNNING�	CANCELLED�CANCELLED_AND_NOTIFIED�FINISHED�pending�running�	cancelled�finishedzconcurrent.futuresc@seZdZdZdS)�Errorz-Base class for all future-related exceptions.N��__name__�
__module__�__qualname__�__doc__�rr�0/usr/lib64/python3.8/concurrent/futures/_base.pyr,src@seZdZdZdS)�CancelledErrorzThe Future was cancelled.Nrrrrrr0src@seZdZdZdS)�TimeoutErrorz*The operation exceeded the given deadline.Nrrrrrr4src@seZdZdZdS)�InvalidStateErrorz+The operation is not allowed in this state.Nrrrrrr8src@s0eZdZdZdd�Zdd�Zdd�Zdd	�Zd
S)�_Waiterz;Provides the event that wait() and as_completed() block on.cCst��|_g|_dS�N)�	threadingZEvent�event�finished_futures��selfrrr�__init__>s
z_Waiter.__init__cCs|j�|�dSr�r�append�r �futurerrr�
add_resultBsz_Waiter.add_resultcCs|j�|�dSrr"r$rrr�
add_exceptionEsz_Waiter.add_exceptioncCs|j�|�dSrr"r$rrr�
add_cancelledHsz_Waiter.add_cancelledN)rrrrr!r&r'r(rrrrr<s
rcsDeZdZdZ�fdd�Z�fdd�Z�fdd�Z�fdd	�Z�ZS)
�_AsCompletedWaiterzUsed by as_completed().cstt|���t��|_dSr)�superr)r!r�Lock�lockr��	__class__rrr!Nsz_AsCompletedWaiter.__init__c	s0|j� tt|��|�|j��W5QRXdSr)r,r*r)r&r�setr$r-rrr&Rsz_AsCompletedWaiter.add_resultc	s0|j� tt|��|�|j��W5QRXdSr)r,r*r)r'rr/r$r-rrr'Wsz _AsCompletedWaiter.add_exceptionc	s0|j� tt|��|�|j��W5QRXdSr)r,r*r)r(rr/r$r-rrr(\sz _AsCompletedWaiter.add_cancelled)	rrrrr!r&r'r(�
__classcell__rrr-rr)Ks
r)cs8eZdZdZ�fdd�Z�fdd�Z�fdd�Z�ZS)�_FirstCompletedWaiterz*Used by wait(return_when=FIRST_COMPLETED).cst��|�|j��dSr)r*r&rr/r$r-rrr&dsz _FirstCompletedWaiter.add_resultcst��|�|j��dSr)r*r'rr/r$r-rrr'hsz#_FirstCompletedWaiter.add_exceptioncst��|�|j��dSr)r*r(rr/r$r-rrr(lsz#_FirstCompletedWaiter.add_cancelled)rrrrr&r'r(r0rrr-rr1asr1csLeZdZdZ�fdd�Zdd�Z�fdd�Z�fdd	�Z�fd
d�Z�Z	S)�_AllCompletedWaiterz<Used by wait(return_when=FIRST_EXCEPTION and ALL_COMPLETED).cs$||_||_t��|_t���dSr)�num_pending_calls�stop_on_exceptionrr+r,r*r!)r r3r4r-rrr!ss
z_AllCompletedWaiter.__init__c	Cs4|j�$|jd8_|js&|j��W5QRXdS)N�)r,r3rr/rrrr�_decrement_pending_callsysz,_AllCompletedWaiter._decrement_pending_callscst��|�|��dSr)r*r&r6r$r-rrr&sz_AllCompletedWaiter.add_resultcs*t��|�|jr|j��n|��dSr)r*r'r4rr/r6r$r-rrr'�sz!_AllCompletedWaiter.add_exceptioncst��|�|��dSr)r*r(r6r$r-rrr(�sz!_AllCompletedWaiter.add_cancelled)
rrrrr!r6r&r'r(r0rrr-rr2psr2c@s(eZdZdZdd�Zdd�Zdd�ZdS)	�_AcquireFutureszDA context manager that does an ordered acquire of Future conditions.cCst|td�|_dS)N)�key)�sorted�id�futures)r r;rrrr!�sz_AcquireFutures.__init__cCs|jD]}|j��qdSr)r;�
_condition�acquirer$rrr�	__enter__�s
z_AcquireFutures.__enter__cGs|jD]}|j��qdSr)r;r<�release)r �argsr%rrr�__exit__�s
z_AcquireFutures.__exit__N)rrrrr!r>rArrrrr7�sr7cCs�|tkrt�}nZ|tkr t�}nJtdd�|D��}|tkrHt|dd�}n"|tkr^t|dd�}ntd|��|D]}|j	�
|�qn|S)Ncss|]}|jttfkVqdSr��_stater	r
��.0�frrr�	<genexpr>�sz._create_and_install_waiters.<locals>.<genexpr>T)r4FzInvalid return condition: %r)rr)rr1�sumrr2r�
ValueError�_waitersr#)�fs�return_when�waiterZ
pending_countrFrrr�_create_and_install_waiters�s�rNc	csP|rL|d}|D]}|�|�q|j�|j�|�W5QRX~|��VqdS)a~
    Iterate on the list *fs*, yielding finished futures one by one in
    reverse order.
    Before yielding a future, *waiter* is removed from its waiters
    and the future is removed from each set in the collection of sets
    *ref_collect*.

    The aim of this function is to avoid keeping stale references after
    the future is yielded and before the iterator resumes.
    ���N)�remover<rJ�pop)rKrM�ref_collectrFZfutures_setrrr�_yield_finished_futures�srSc	csB|dk	r|t��}t|�}t|�}t|��*tdd�|D��}||}t|t�}W5QRXt|�}z�t|||fd�EdH|�r|dkr�d}n(|t��}|dkr�tdt|�|f��|j
�|�|j�|j}g|_|j
��W5QRX|��t||||fd�EdHq|W5|D]$}|j�|j	�
|�W5QRX�qXdS)anAn iterator over the given futures that yields each as it completes.

    Args:
        fs: The sequence of Futures (possibly created by different Executors) to
            iterate over.
        timeout: The maximum number of seconds to wait. If None, then there
            is no limit on the wait time.

    Returns:
        An iterator that yields the given Futures as they complete (finished or
        cancelled). If any given Futures are duplicated, they will be returned
        once.

    Raises:
        TimeoutError: If the entire result iterator could not be generated
            before the given timeout.
    Ncss |]}|jttfkr|VqdSrrBrDrrrrG�s�zas_completed.<locals>.<genexpr>)rRrz%d (of %d) futures unfinished)�time�	monotonicr/�lenr7rNr�listr<rJrPrSrr�waitr,r�clear�reverse)	rK�timeout�end_timeZ
total_futuresrrrMrFZwait_timeoutrrr�as_completed�sL
�����r]�DoneAndNotDoneFuturesz
done not_donec
Cs
t|���tdd�|D��}t|�|}|tkrJ|rJt||�W5QR�S|tkr~|r~tdd�|D��r~t||�W5QR�St|�t|�kr�t||�W5QR�St||�}W5QRX|j�	|�|D]"}|j
�|j�|�W5QRXq�|�
|j�t|t|�|�S)aWait for the futures in the given sequence to complete.

    Args:
        fs: The sequence of Futures (possibly created by different Executors) to
            wait upon.
        timeout: The maximum number of seconds to wait. If None, then there
            is no limit on the wait time.
        return_when: Indicates when this function should return. The options
            are:

            FIRST_COMPLETED - Return when any future finishes or is
                              cancelled.
            FIRST_EXCEPTION - Return when any future finishes by raising an
                              exception. If no future raises an exception
                              then it is equivalent to ALL_COMPLETED.
            ALL_COMPLETED -   Return when all futures finish or are cancelled.

    Returns:
        A named 2-tuple of sets. The first set, named 'done', contains the
        futures that completed (is finished or cancelled) before the wait
        completed. The second set, named 'not_done', contains uncompleted
        futures.
    css |]}|jttfkr|VqdSrrBrDrrrrG!s�zwait.<locals>.<genexpr>css&|]}|��s|��dk	r|VqdSr)r
�	exceptionrDrrrrG(s�)r7r/rr^r�anyrVrNrrXr<rJrP�updater)rKr[rL�doneZnot_donerMrFrrrrXs"
rXc@s�eZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�Zdd�Zddd�Z
d dd�Zdd�Zdd�Zdd�ZdS)!�Futurez5Represents the result of an asynchronous computation.cCs,t��|_t|_d|_d|_g|_g|_dS)z8Initializes the future. Should not be called by clients.N)	rZ	Conditionr<rrC�_result�
_exceptionrJ�_done_callbacksrrrrr!<s
zFuture.__init__c	Cs>|jD]2}z||�Wqtk
r6t�d|�YqXqdS)N�!exception calling callback for %r)rf�	Exception�LOGGERr_)r �callbackrrr�_invoke_callbacksEs

zFuture._invoke_callbacksc
Cs�|j��|jtkrx|jrHd|jjt|�t|j|jjjfW5QR�Sd|jjt|�t|j|jjjfW5QR�Sd|jjt|�t|jfW5QR�SQRXdS)Nz<%s at %#x state=%s raised %s>z <%s at %#x state=%s returned %s>z<%s at %#x state=%s>)	r<rCr
rer.rr:�_STATE_TO_DESCRIPTION_MAPrdrrrr�__repr__Ls(
���zFuture.__repr__c	Csf|j�N|jttfkr$W5QR�dS|jttfkr@W5QR�dSt|_|j��W5QRX|��dS)z�Cancel the future if possible.

        Returns True if the future was cancelled, False otherwise. A future
        cannot be cancelled if it is running or has already completed.
        FT)r<rCrr
rr	�
notify_allrkrrrr�cancel`sz
Future.cancelc
Cs,|j�|jttfkW5QR�SQRXdS)z(Return True if the future was cancelled.N)r<rCrr	rrrrr
sszFuture.cancelledc
Cs(|j�|jtkW5QR�SQRXdS)z1Return True if the future is currently executing.N)r<rCrrrrrrxszFuture.runningc
Cs.|j�|jtttfkW5QR�SQRXdS)z>Return True of the future was cancelled or finished executing.N)r<rCrr	r
rrrrrb}szFuture.donecCs$|jrz
|j�W5d}Xn|jSdSr)rerdrrrrZ__get_result�s

zFuture.__get_resultc	Csn|j�0|jtttfkr2|j�|�W5QR�dSW5QRXz||�Wn tk
rht�	d|�YnXdS)a%Attaches a callable that will be called when the future finishes.

        Args:
            fn: A callable that will be called with this future as its only
                argument when the future completes or is cancelled. The callable
                will always be called by a thread in the same process in which
                it was added. If the future has already completed or been
                cancelled then the callable will be called immediately. These
                callables are called in the order that they were added.
        Nrg)
r<rCrr	r
rfr#rhrir_)r �fnrrr�add_done_callback�szFuture.add_done_callbackNc
Cs�z�|j��|jttfkr t��n"|jtkrB|��W5QR�W�ZS|j�|�|jttfkrdt��n(|jtkr�|��W5QR�W�St��W5QRXW5d}XdS)aBReturn the result of the call that the future represents.

        Args:
            timeout: The number of seconds to wait for the result if the future
                isn't done. If None, then there is no limit on the wait time.

        Returns:
            The result of the call that the future represents.

        Raises:
            CancelledError: If the future was cancelled.
            TimeoutError: If the future didn't finish executing before the given
                timeout.
            Exception: If the call raised then that exception will be raised.
        N)	r<rCrr	rr
�_Future__get_resultrXr�r r[rrr�result�s

z
Future.resultc
Cs�|j�||jttfkrt��n|jtkr:|jW5QR�S|j�|�|jttfkr\t��n"|jtkrx|jW5QR�St��W5QRXdS)aUReturn the exception raised by the call that the future represents.

        Args:
            timeout: The number of seconds to wait for the exception if the
                future isn't done. If None, then there is no limit on the wait
                time.

        Returns:
            The exception raised by the call that the future represents or None
            if the call completed without raising.

        Raises:
            CancelledError: If the future was cancelled.
            TimeoutError: If the future didn't finish executing before the given
                timeout.
        N)	r<rCrr	rr
rerXrrsrrrr_�s

zFuture.exceptionc	Cs�|j�t|jtkr<t|_|jD]}|�|�qW5QR�dS|jtkrZt|_W5QR�dSt�	dt
|�|j�td��W5QRXdS)a�Mark the future as running or process any cancel notifications.

        Should only be used by Executor implementations and unit tests.

        If the future has been cancelled (cancel() was called and returned
        True) then any threads waiting on the future completing (though calls
        to as_completed() or wait()) are notified and False is returned.

        If the future was not cancelled then it is put in the running state
        (future calls to running() will return True) and True is returned.

        This method should be called by Executor implementations before
        executing the work associated with this future. If this method returns
        False then the work should not be executed.

        Returns:
            False if the Future was cancelled, True otherwise.

        Raises:
            RuntimeError: if this method was already called or if set_result()
                or set_exception() was called.
        FTz!Future %s in unexpected state: %szFuture in unexpected stateN)r<rCrr	rJr(rrriZcriticalr:�RuntimeError)r rMrrr�set_running_or_notify_cancel�s


�z#Future.set_running_or_notify_cancelc	Csl|j�T|jttthkr*td�|j|���||_t|_|jD]}|�	|�q<|j�
�W5QRX|��dS)z�Sets the return value of work associated with the future.

        Should only be used by Executor implementations and unit tests.
        �{}: {!r}N)r<rCrr	r
r�formatrdrJr&rnrk)r rtrMrrr�
set_result
s
zFuture.set_resultc	Csl|j�T|jttthkr*td�|j|���||_t|_|jD]}|�	|�q<|j�
�W5QRX|��dS)z�Sets the result of the future as being the given exception.

        Should only be used by Executor implementations and unit tests.
        rwN)r<rCrr	r
rrxrerJr'rnrk)r r_rMrrr�
set_exceptions
zFuture.set_exception)N)N)rrrrr!rkrmror
rrbrrrqrtr_rvryrzrrrrrc9s	

#
"(rcc@sHeZdZdZdd�Zde_ddd�dd	�Zddd�Zd
d�Zdd�Z	dS)�ExecutorzCThis is an abstract base class for concrete asynchronous executors.cOs\t|�dkrnD|std��n6d|kr>ddl}|jdtdd�ntdt|�d	��t��dS)
a Submits a callable to be executed with the given arguments.

        Schedules the callable to be executed as fn(*args, **kwargs) and returns
        a Future instance representing the execution of the callable.

        Returns:
            A Future representing the given call.
        �z:descriptor 'submit' of 'Executor' object needs an argumentrprNz.Passing 'fn' as keyword argument is deprecated)�
stacklevelz6submit expected at least 1 positional argument, got %dr5)rV�	TypeError�warnings�warn�DeprecationWarning�NotImplementedError)r@�kwargsrrrr�submit.s	
�
�zExecutor.submitz($self, fn, /, *args, **kwargs)Nr5)r[�	chunksizecsB�dk	r�t�����fdd�t|�D�����fdd�}|�S)a}Returns 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: The size of the chunks the iterable will be broken into
                before being passed to a child process. This argument is only
                used by ProcessPoolExecutor; it is ignored by
                ThreadPoolExecutor.

        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.
        Ncsg|]}�j�f|���qSr)r�)rEr@)rpr rr�
<listcomp>`sz Executor.map.<locals>.<listcomp>c	3s\zB����r@�dkr&�����Vq
�����t���Vq
W5�D]}|��qHXdSr)rorZrQrtrTrU)r%)r\rKr[rr�result_iteratordsz%Executor.map.<locals>.result_iterator)rTrU�zip)r rpr[r��	iterablesr�r)r\rprKr r[r�mapGs

zExecutor.mapTcCsdS)a�Clean-up the resources associated with the Executor.

        It is safe to call this method several times. Otherwise, no other
        methods can be called after this one.

        Args:
            wait: If True then shutdown will not return until all running
                futures have finished executing and the resources used by the
                executor have been reclaimed.
        Nr)r rXrrr�shutdownsszExecutor.shutdowncCs|Srrrrrrr>�szExecutor.__enter__cCs|jdd�dS)NT)rXF)r�)r �exc_typeZexc_valZexc_tbrrrrA�szExecutor.__exit__)T)
rrrrr��__text_signature__r�r�r>rArrrrr{+s,

r{c@seZdZdZdS)�BrokenExecutorzR
    Raised when a executor has become non-functional after a severe failure.
    Nrrrrrr��sr�)N)'�
__author__�collectionsZloggingrrTrrrrrrrr	r
Z_FUTURE_STATESrlZ	getLoggerrirhrrrr�objectrr)r1r2r7rNrSr]�
namedtupler^rXrcr{rur�rrrr�<module>sh�	�	

>�1s]PK�j�\��65��'__pycache__/thread.cpython-38.opt-1.pycnu�[���U

e5d@"�@s�dZdZddlZddlmZddlZddlZddlZddlZddl	Z	e�
�Zdadd�Z
e�e
�Gdd	�d	e�Zd
d�ZGdd
�d
ej�ZGdd�dej�ZdS)zImplements ThreadPoolExecutor.z"Brian Quinlan (brian@sweetapp.com)�N)�_baseFcCsBdatt���}|D]\}}|�d�q|D]\}}|��q,dS�NT)�	_shutdown�list�_threads_queues�items�put�join)r�t�q�r�1/usr/lib64/python3.8/concurrent/futures/thread.py�_python_exit!src@seZdZdd�Zdd�ZdS)�	_WorkItemcCs||_||_||_||_dS�N)�future�fn�args�kwargs)�selfrrrrrrr
�__init__.sz_WorkItem.__init__c
Csf|j��sdSz|j|j|j�}Wn2tk
rT}z|j�|�d}W5d}~XYnX|j�|�dSr)rZset_running_or_notify_cancelrrr�
BaseException�
set_exceptionZ
set_result)r�result�excrrr
�run4s
z
_WorkItem.runN)�__name__�
__module__�__qualname__rrrrrr
r-srcCs�|dk	rRz||�Wn<tk
rPtjjddd�|�}|dk	rJ|��YdSXzx|jdd�}|dk	r�|��~|�}|dk	r�|j��~qT|�}t	s�|dks�|j	r�|dk	r�d|_	|�
d�WdS~qTWn$tk
r�tjjddd�YnXdS)NzException in initializer:T)�exc_info)�blockzException in worker)rrZLOGGERZcritical�_initializer_failed�getr�_idle_semaphore�releaserr)Zexecutor_referenceZ
work_queue�initializer�initargsZexecutor�	work_itemrrr
�_workerBs8

r(c@seZdZdZdS)�BrokenThreadPoolzR
    Raised when a worker thread in a ThreadPoolExecutor failed initializing.
    N)rrr�__doc__rrrr
r)msr)c@sfeZdZe��jZddd�Zdd�Ze	j
jje_e	j
jje_dd	�Z
d
d�Zdd
d�Ze	j
jje_dS)�ThreadPoolExecutorN�rcCs�|dkrtdt��pdd�}|dkr.td��|dk	rFt|�sFtd��||_t��|_	t
�d�|_t
�|_d|_d|_t
��|_|p�d	|��|_||_||_dS)
a�Initializes a new ThreadPoolExecutor instance.

        Args:
            max_workers: The maximum number of threads that can be used to
                execute the given calls.
            thread_name_prefix: An optional name prefix to give our threads.
            initializer: A callable used to initialize worker threads.
            initargs: A tuple of arguments to pass to the initializer.
        N� ��rz"max_workers must be greater than 0zinitializer must be a callableFzThreadPoolExecutor-%d)�min�os�	cpu_count�
ValueError�callable�	TypeError�_max_workers�queueZSimpleQueue�_work_queue�	threadingZ	Semaphorer#�set�_threads�_brokenrZLock�_shutdown_lock�_counter�_thread_name_prefix�_initializer�	_initargs)rZmax_workersZthread_name_prefixr%r&rrr
rxs$


�zThreadPoolExecutor.__init__c
Os�t|�dkr|^}}}nV|s&td��nHd|krZ|�d�}|^}}ddl}|jdtdd�ntdt|�d��|j�f|jr�t|j��|j	r�t
d	��t	r�t
d
��t��}t
||||�}|j�|�|��|W5QR�SQRXdS)N�zDdescriptor 'submit' of 'ThreadPoolExecutor' object needs an argumentrrz.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)�lenr5�pop�warnings�warn�DeprecationWarningr=r<r)r�RuntimeErrorrZFuturerr8r�_adjust_thread_count)rrrrrF�f�wrrr
�submit�s6

�
�
zThreadPoolExecutor.submitcCs�|jjdd�rdS|jfdd�}t|j�}||jkr�d|jp>||f}tj|t	t
�||�|j|j|j
fd�}d|_|��|j�|�|jt|<dS)Nr)ZtimeoutcSs|�d�dSr)r)�_rrrr
�
weakref_cb�sz;ThreadPoolExecutor._adjust_thread_count.<locals>.weakref_cbz%s_%d)�name�targetrT)r#�acquirer8rDr;r6r?r9ZThreadr(�weakref�refr@rAZdaemon�start�addr)rrOZnum_threadsZthread_namer
rrr
rJ�s&


�
��z'ThreadPoolExecutor._adjust_thread_countc	Csb|j�Rd|_z|j��}Wntjk
r6YqTYnX|dk	r|j�t|j��qW5QRXdS)NzBA thread initializer failed, the thread pool is not usable anymore)	r=r<r8Z
get_nowaitr7ZEmptyrrr))rr'rrr
r!�s
z&ThreadPoolExecutor._initializer_failedTc	Cs@|j�d|_|j�d�W5QRX|r<|jD]}|��q.dSr)r=rr8rr;r	)r�waitr
rrr
�shutdown�s
zThreadPoolExecutor.shutdown)Nr,Nr)T)rrr�	itertools�count�__next__r>rrMr�Executor�__text_signature__r*rJr!rXrrrr
r+ss
�
& 
r+)r*�
__author__�atexitZconcurrent.futuresrrYr7r9rSr1�WeakKeyDictionaryrrr�register�objectrr(ZBrokenExecutorr)r\r+rrrr
�<module>s 	
+PK�j�\��Q�

)__pycache__/__init__.cpython-38.opt-2.pycnu�[���U

e5d�@sPdZddlmZmZmZmZmZmZmZm	Z	m
Z
mZmZdZ
dd�Zdd�ZdS)	z"Brian Quinlan (brian@sweetapp.com)�)�FIRST_COMPLETED�FIRST_EXCEPTION�
ALL_COMPLETED�CancelledError�TimeoutError�InvalidStateError�BrokenExecutor�Future�Executor�wait�as_completed)rrrrrrr	r
rr�ProcessPoolExecutor�ThreadPoolExecutorcCstdS)N)�
__author__�__doc__)�__all__�rr�3/usr/lib64/python3.8/concurrent/futures/__init__.py�__dir__$srcCsP|dkrddlm}|a|S|dkr8ddlm}|a|Stdt�d|����dS)Nr
�)r
r)rzmodule z has no attribute )Zprocessr
�threadr�AttributeError�__name__)�nameZpeZterrr�__getattr__(srN)rZconcurrent.futures._baserrrrrrrr	r
rrrrrrrrr�<module>s4PK�j�\��65��!__pycache__/thread.cpython-38.pycnu�[���U

e5d@"�@s�dZdZddlZddlmZddlZddlZddlZddlZddl	Z	e�
�Zdadd�Z
e�e
�Gdd	�d	e�Zd
d�ZGdd
�d
ej�ZGdd�dej�ZdS)zImplements ThreadPoolExecutor.z"Brian Quinlan (brian@sweetapp.com)�N)�_baseFcCsBdatt���}|D]\}}|�d�q|D]\}}|��q,dS�NT)�	_shutdown�list�_threads_queues�items�put�join)r�t�q�r�1/usr/lib64/python3.8/concurrent/futures/thread.py�_python_exit!src@seZdZdd�Zdd�ZdS)�	_WorkItemcCs||_||_||_||_dS�N)�future�fn�args�kwargs)�selfrrrrrrr
�__init__.sz_WorkItem.__init__c
Csf|j��sdSz|j|j|j�}Wn2tk
rT}z|j�|�d}W5d}~XYnX|j�|�dSr)rZset_running_or_notify_cancelrrr�
BaseException�
set_exceptionZ
set_result)r�result�excrrr
�run4s
z
_WorkItem.runN)�__name__�
__module__�__qualname__rrrrrr
r-srcCs�|dk	rRz||�Wn<tk
rPtjjddd�|�}|dk	rJ|��YdSXzx|jdd�}|dk	r�|��~|�}|dk	r�|j��~qT|�}t	s�|dks�|j	r�|dk	r�d|_	|�
d�WdS~qTWn$tk
r�tjjddd�YnXdS)NzException in initializer:T)�exc_info)�blockzException in worker)rrZLOGGERZcritical�_initializer_failed�getr�_idle_semaphore�releaserr)Zexecutor_referenceZ
work_queue�initializer�initargsZexecutor�	work_itemrrr
�_workerBs8

r(c@seZdZdZdS)�BrokenThreadPoolzR
    Raised when a worker thread in a ThreadPoolExecutor failed initializing.
    N)rrr�__doc__rrrr
r)msr)c@sfeZdZe��jZddd�Zdd�Ze	j
jje_e	j
jje_dd	�Z
d
d�Zdd
d�Ze	j
jje_dS)�ThreadPoolExecutorN�rcCs�|dkrtdt��pdd�}|dkr.td��|dk	rFt|�sFtd��||_t��|_	t
�d�|_t
�|_d|_d|_t
��|_|p�d	|��|_||_||_dS)
a�Initializes a new ThreadPoolExecutor instance.

        Args:
            max_workers: The maximum number of threads that can be used to
                execute the given calls.
            thread_name_prefix: An optional name prefix to give our threads.
            initializer: A callable used to initialize worker threads.
            initargs: A tuple of arguments to pass to the initializer.
        N� ��rz"max_workers must be greater than 0zinitializer must be a callableFzThreadPoolExecutor-%d)�min�os�	cpu_count�
ValueError�callable�	TypeError�_max_workers�queueZSimpleQueue�_work_queue�	threadingZ	Semaphorer#�set�_threads�_brokenrZLock�_shutdown_lock�_counter�_thread_name_prefix�_initializer�	_initargs)rZmax_workersZthread_name_prefixr%r&rrr
rxs$


�zThreadPoolExecutor.__init__c
Os�t|�dkr|^}}}nV|s&td��nHd|krZ|�d�}|^}}ddl}|jdtdd�ntdt|�d��|j�f|jr�t|j��|j	r�t
d	��t	r�t
d
��t��}t
||||�}|j�|�|��|W5QR�SQRXdS)N�zDdescriptor 'submit' of 'ThreadPoolExecutor' object needs an argumentrrz.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)�lenr5�pop�warnings�warn�DeprecationWarningr=r<r)r�RuntimeErrorrZFuturerr8r�_adjust_thread_count)rrrrrF�f�wrrr
�submit�s6

�
�
zThreadPoolExecutor.submitcCs�|jjdd�rdS|jfdd�}t|j�}||jkr�d|jp>||f}tj|t	t
�||�|j|j|j
fd�}d|_|��|j�|�|jt|<dS)Nr)ZtimeoutcSs|�d�dSr)r)�_rrrr
�
weakref_cb�sz;ThreadPoolExecutor._adjust_thread_count.<locals>.weakref_cbz%s_%d)�name�targetrT)r#�acquirer8rDr;r6r?r9ZThreadr(�weakref�refr@rAZdaemon�start�addr)rrOZnum_threadsZthread_namer
rrr
rJ�s&


�
��z'ThreadPoolExecutor._adjust_thread_countc	Csb|j�Rd|_z|j��}Wntjk
r6YqTYnX|dk	r|j�t|j��qW5QRXdS)NzBA thread initializer failed, the thread pool is not usable anymore)	r=r<r8Z
get_nowaitr7ZEmptyrrr))rr'rrr
r!�s
z&ThreadPoolExecutor._initializer_failedTc	Cs@|j�d|_|j�d�W5QRX|r<|jD]}|��q.dSr)r=rr8rr;r	)r�waitr
rrr
�shutdown�s
zThreadPoolExecutor.shutdown)Nr,Nr)T)rrr�	itertools�count�__next__r>rrMr�Executor�__text_signature__r*rJr!rXrrrr
r+ss
�
& 
r+)r*�
__author__�atexitZconcurrent.futuresrrYr7r9rSr1�WeakKeyDictionaryrrr�register�objectrr(ZBrokenExecutorr)r\r+rrrr
�<module>s 	
+PK�j�\&B�
Q7Q7&__pycache__/_base.cpython-38.opt-2.pycnu�[���U

e5dY�
@spdZddlZddlZddlZddlZdZdZdZdZdZ	dZ
d	Zd
ZdZ
e	e
eee
gZe	de
d
edede
diZe�d�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd �d e�ZGd!d"�d"e�Zd#d$�Zd%d&�Zd3d'd(�Ze� d)d*�Z!defd+d,�Z"Gd-d.�d.e�Z#Gd/d0�d0e�Z$Gd1d2�d2e%�Z&dS)4z"Brian Quinlan (brian@sweetapp.com)�N�FIRST_COMPLETED�FIRST_EXCEPTION�
ALL_COMPLETED�
_AS_COMPLETED�PENDING�RUNNING�	CANCELLED�CANCELLED_AND_NOTIFIED�FINISHED�pending�running�	cancelled�finishedzconcurrent.futuresc@seZdZdS)�ErrorN��__name__�
__module__�__qualname__�rr�0/usr/lib64/python3.8/concurrent/futures/_base.pyr,src@seZdZdS)�CancelledErrorNrrrrrr0src@seZdZdS)�TimeoutErrorNrrrrrr4src@seZdZdS)�InvalidStateErrorNrrrrrr8src@s,eZdZdd�Zdd�Zdd�Zdd�Zd	S)
�_WaitercCst��|_g|_dS�N)�	threadingZEvent�event�finished_futures��selfrrr�__init__>s
z_Waiter.__init__cCs|j�|�dSr�r�append�r�futurerrr�
add_resultBsz_Waiter.add_resultcCs|j�|�dSrr!r#rrr�
add_exceptionEsz_Waiter.add_exceptioncCs|j�|�dSrr!r#rrr�
add_cancelledHsz_Waiter.add_cancelledN)rrrr r%r&r'rrrrr<srcs@eZdZ�fdd�Z�fdd�Z�fdd�Z�fdd�Z�ZS)	�_AsCompletedWaitercstt|���t��|_dSr)�superr(r r�Lock�lockr��	__class__rrr Nsz_AsCompletedWaiter.__init__c	s0|j� tt|��|�|j��W5QRXdSr)r+r)r(r%r�setr#r,rrr%Rsz_AsCompletedWaiter.add_resultc	s0|j� tt|��|�|j��W5QRXdSr)r+r)r(r&rr.r#r,rrr&Wsz _AsCompletedWaiter.add_exceptionc	s0|j� tt|��|�|j��W5QRXdSr)r+r)r(r'rr.r#r,rrr'\sz _AsCompletedWaiter.add_cancelled)rrrr r%r&r'�
__classcell__rrr,rr(Ksr(cs4eZdZ�fdd�Z�fdd�Z�fdd�Z�ZS)�_FirstCompletedWaitercst��|�|j��dSr)r)r%rr.r#r,rrr%dsz _FirstCompletedWaiter.add_resultcst��|�|j��dSr)r)r&rr.r#r,rrr&hsz#_FirstCompletedWaiter.add_exceptioncst��|�|j��dSr)r)r'rr.r#r,rrr'lsz#_FirstCompletedWaiter.add_cancelled)rrrr%r&r'r/rrr,rr0asr0csHeZdZ�fdd�Zdd�Z�fdd�Z�fdd�Z�fd	d
�Z�ZS)�_AllCompletedWaitercs$||_||_t��|_t���dSr)�num_pending_calls�stop_on_exceptionrr*r+r)r )rr2r3r,rrr ss
z_AllCompletedWaiter.__init__c	Cs4|j�$|jd8_|js&|j��W5QRXdS)N�)r+r2rr.rrrr�_decrement_pending_callsysz,_AllCompletedWaiter._decrement_pending_callscst��|�|��dSr)r)r%r5r#r,rrr%sz_AllCompletedWaiter.add_resultcs*t��|�|jr|j��n|��dSr)r)r&r3rr.r5r#r,rrr&�sz!_AllCompletedWaiter.add_exceptioncst��|�|��dSr)r)r'r5r#r,rrr'�sz!_AllCompletedWaiter.add_cancelled)	rrrr r5r%r&r'r/rrr,rr1ps
r1c@s$eZdZdd�Zdd�Zdd�ZdS)�_AcquireFuturescCst|td�|_dS)N)�key)�sorted�id�futures)rr:rrrr �sz_AcquireFutures.__init__cCs|jD]}|j��qdSr)r:�
_condition�acquirer#rrr�	__enter__�s
z_AcquireFutures.__enter__cGs|jD]}|j��qdSr)r:r;�release)r�argsr$rrr�__exit__�s
z_AcquireFutures.__exit__N)rrrr r=r@rrrrr6�sr6cCs�|tkrt�}nZ|tkr t�}nJtdd�|D��}|tkrHt|dd�}n"|tkr^t|dd�}ntd|��|D]}|j	�
|�qn|S)Ncss|]}|jttfkVqdSr��_stater	r
��.0�frrr�	<genexpr>�sz._create_and_install_waiters.<locals>.<genexpr>T)r3FzInvalid return condition: %r)rr(rr0�sumrr1r�
ValueError�_waitersr")�fs�return_when�waiterZ
pending_countrErrr�_create_and_install_waiters�s�rMc	csP|rL|d}|D]}|�|�q|j�|j�|�W5QRX~|��VqdS)N���)�remover;rI�pop)rJrL�ref_collectrEZfutures_setrrr�_yield_finished_futures�srRc	csB|dk	r|t��}t|�}t|�}t|��*tdd�|D��}||}t|t�}W5QRXt|�}z�t|||fd�EdH|�r|dkr�d}n(|t��}|dkr�tdt|�|f��|j
�|�|j�|j}g|_|j
��W5QRX|��t||||fd�EdHq|W5|D]$}|j�|j	�
|�W5QRX�qXdS)Ncss |]}|jttfkr|VqdSrrArCrrrrF�s�zas_completed.<locals>.<genexpr>)rQrz%d (of %d) futures unfinished)�time�	monotonicr.�lenr6rMr�listr;rIrOrRrr�waitr+r�clear�reverse)	rJ�timeout�end_timeZ
total_futuresrrrLrEZwait_timeoutrrr�as_completed�sL
�����r\�DoneAndNotDoneFuturesz
done not_donec
Cs
t|���tdd�|D��}t|�|}|tkrJ|rJt||�W5QR�S|tkr~|r~tdd�|D��r~t||�W5QR�St|�t|�kr�t||�W5QR�St||�}W5QRX|j�	|�|D]"}|j
�|j�|�W5QRXq�|�
|j�t|t|�|�S)Ncss |]}|jttfkr|VqdSrrArCrrrrF!s�zwait.<locals>.<genexpr>css&|]}|��s|��dk	r|VqdSr)r
�	exceptionrCrrrrF(s�)r6r.rr]r�anyrUrMrrWr;rIrO�updater)rJrZrK�doneZnot_donerLrErrrrWs"
rWc@s�eZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
dd�Zddd�Zddd�Z
dd�Zdd�Zdd�ZdS) �FuturecCs,t��|_t|_d|_d|_g|_g|_dSr)	rZ	Conditionr;rrB�_result�
_exceptionrI�_done_callbacksrrrrr <s
zFuture.__init__c	Cs>|jD]2}z||�Wqtk
r6t�d|�YqXqdS�Nz!exception calling callback for %r)re�	Exception�LOGGERr^)r�callbackrrr�_invoke_callbacksEs

zFuture._invoke_callbacksc
Cs�|j��|jtkrx|jrHd|jjt|�t|j|jjjfW5QR�Sd|jjt|�t|j|jjjfW5QR�Sd|jjt|�t|jfW5QR�SQRXdS)Nz<%s at %#x state=%s raised %s>z <%s at %#x state=%s returned %s>z<%s at %#x state=%s>)	r;rBr
rdr-rr9�_STATE_TO_DESCRIPTION_MAPrcrrrr�__repr__Ls(
���zFuture.__repr__c	Csf|j�N|jttfkr$W5QR�dS|jttfkr@W5QR�dSt|_|j��W5QRX|��dS)NFT)r;rBrr
rr	�
notify_allrjrrrr�cancel`sz
Future.cancelc
Cs,|j�|jttfkW5QR�SQRXdSr)r;rBrr	rrrrr
sszFuture.cancelledc
Cs(|j�|jtkW5QR�SQRXdSr)r;rBrrrrrrxszFuture.runningc
Cs.|j�|jtttfkW5QR�SQRXdSr)r;rBrr	r
rrrrra}szFuture.donecCs$|jrz
|j�W5d}Xn|jSdSr)rdrcrrrrZ__get_result�s

zFuture.__get_resultc	Csn|j�0|jtttfkr2|j�|�W5QR�dSW5QRXz||�Wn tk
rht�	d|�YnXdSrf)
r;rBrr	r
rer"rgrhr^)r�fnrrr�add_done_callback�szFuture.add_done_callbackNc
Cs�z�|j��|jttfkr t��n"|jtkrB|��W5QR�W�ZS|j�|�|jttfkrdt��n(|jtkr�|��W5QR�W�St��W5QRXW5d}XdSr)	r;rBrr	rr
�_Future__get_resultrWr�rrZrrr�result�s

z
Future.resultc
Cs�|j�||jttfkrt��n|jtkr:|jW5QR�S|j�|�|jttfkr\t��n"|jtkrx|jW5QR�St��W5QRXdSr)	r;rBrr	rr
rdrWrrrrrrr^�s

zFuture.exceptionc	Cs�|j�t|jtkr<t|_|jD]}|�|�qW5QR�dS|jtkrZt|_W5QR�dSt�	dt
|�|j�td��W5QRXdS)NFTz!Future %s in unexpected state: %szFuture in unexpected state)r;rBrr	rIr'rrrhZcriticalr9�RuntimeError)rrLrrr�set_running_or_notify_cancel�s


�z#Future.set_running_or_notify_cancelc	Csl|j�T|jttthkr*td�|j|���||_t|_|jD]}|�	|�q<|j�
�W5QRX|��dS�Nz{}: {!r})r;rBrr	r
r�formatrcrIr%rmrj)rrsrLrrr�
set_result
s
zFuture.set_resultc	Csl|j�T|jttthkr*td�|j|���||_t|_|jD]}|�	|�q<|j�
�W5QRX|��dSrv)r;rBrr	r
rrwrdrIr&rmrj)rr^rLrrr�
set_exceptions
zFuture.set_exception)N)N)rrrr rjrlrnr
rrarqrprsr^rurxryrrrrrb9s	

#
"(rbc@sDeZdZdd�Zde_ddd�dd�Zdd
d�Zdd
�Zdd�ZdS)�ExecutorcOs\t|�dkrnD|std��n6d|kr>ddl}|jdtdd�ntdt|�d��t��dS)	N�z:descriptor 'submit' of 'Executor' object needs an argumentrorz.Passing 'fn' as keyword argument is deprecated)�
stacklevelz6submit expected at least 1 positional argument, got %dr4)rU�	TypeError�warnings�warn�DeprecationWarning�NotImplementedError)r?�kwargsr~rrr�submit.s	
�
�zExecutor.submitz($self, fn, /, *args, **kwargs)Nr4)rZ�	chunksizecsB�dk	r�t�����fdd�t|�D�����fdd�}|�S)Ncsg|]}�j�f|���qSr)r�)rDr?)rorrr�
<listcomp>`sz Executor.map.<locals>.<listcomp>c	3s\zB����r@�dkr&�����Vq
�����t���Vq
W5�D]}|��qHXdSr)rnrYrPrsrSrT)r$)r[rJrZrr�result_iteratordsz%Executor.map.<locals>.result_iterator)rSrT�zip)rrorZr��	iterablesr�r)r[rorJrrZr�mapGs

zExecutor.mapTcCsdSrr)rrWrrr�shutdownsszExecutor.shutdowncCs|Srrrrrrr=�szExecutor.__enter__cCs|jdd�dS)NT)rWF)r�)r�exc_typeZexc_valZexc_tbrrrr@�szExecutor.__exit__)T)	rrrr��__text_signature__r�r�r=r@rrrrrz+s,

rzc@seZdZdS)�BrokenExecutorNrrrrrr��sr�)N)'�
__author__�collectionsZloggingrrSrrrrrrrr	r
Z_FUTURE_STATESrkZ	getLoggerrhrgrrrr�objectrr(r0r1r6rMrRr\�
namedtupler]rWrbrzrtr�rrrr�<module>sh�	�	

>�1s]PK�j�\,C|VV#__pycache__/__init__.cpython-38.pycnu�[���U

e5d�@sTdZdZddlmZmZmZmZmZmZm	Z	m
Z
mZmZm
Z
dZdd�Zdd�Zd	S)
z?Execute computations asynchronously using threads or processes.z"Brian Quinlan (brian@sweetapp.com)�)�FIRST_COMPLETED�FIRST_EXCEPTION�
ALL_COMPLETED�CancelledError�TimeoutError�InvalidStateError�BrokenExecutor�Future�Executor�wait�as_completed)rrrrrrr	r
rr�ProcessPoolExecutor�ThreadPoolExecutorcCstdS)N)�
__author__�__doc__)�__all__�rr�3/usr/lib64/python3.8/concurrent/futures/__init__.py�__dir__$srcCsP|dkrddlm}|a|S|dkr8ddlm}|a|Stdt�d|����dS)Nr
�)r
r)rzmodule z has no attribute )Zprocessr
�threadr�AttributeError�__name__)�nameZpeZterrr�__getattr__(srN)rrZconcurrent.futures._baserrrrrrrr	r
rrrrrrrrr�<module>s
4PK�j�\,C|VV)__pycache__/__init__.cpython-38.opt-1.pycnu�[���U

e5d�@sTdZdZddlmZmZmZmZmZmZm	Z	m
Z
mZmZm
Z
dZdd�Zdd�Zd	S)
z?Execute computations asynchronously using threads or processes.z"Brian Quinlan (brian@sweetapp.com)�)�FIRST_COMPLETED�FIRST_EXCEPTION�
ALL_COMPLETED�CancelledError�TimeoutError�InvalidStateError�BrokenExecutor�Future�Executor�wait�as_completed)rrrrrrr	r
rr�ProcessPoolExecutor�ThreadPoolExecutorcCstdS)N)�
__author__�__doc__)�__all__�rr�3/usr/lib64/python3.8/concurrent/futures/__init__.py�__dir__$srcCsP|dkrddlm}|a|S|dkr8ddlm}|a|Stdt�d|����dS)Nr
�)r
r)rzmodule z has no attribute )Zprocessr
�threadr�AttributeError�__name__)�nameZpeZterrr�__getattr__(srN)rrZconcurrent.futures._baserrrrrrrr	r
rrrrrrrrr�<module>s
4PK�j�\$��ڶU�U&__pycache__/_base.cpython-38.opt-1.pycnu�[���U

e5dY�
@spdZddlZddlZddlZddlZdZdZdZdZdZ	dZ
d	Zd
ZdZ
e	e
eee
gZe	de
d
edede
diZe�d�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd �d e�ZGd!d"�d"e�Zd#d$�Zd%d&�Zd3d'd(�Ze� d)d*�Z!defd+d,�Z"Gd-d.�d.e�Z#Gd/d0�d0e�Z$Gd1d2�d2e%�Z&dS)4z"Brian Quinlan (brian@sweetapp.com)�N�FIRST_COMPLETED�FIRST_EXCEPTION�
ALL_COMPLETED�
_AS_COMPLETED�PENDING�RUNNING�	CANCELLED�CANCELLED_AND_NOTIFIED�FINISHED�pending�running�	cancelled�finishedzconcurrent.futuresc@seZdZdZdS)�Errorz-Base class for all future-related exceptions.N��__name__�
__module__�__qualname__�__doc__�rr�0/usr/lib64/python3.8/concurrent/futures/_base.pyr,src@seZdZdZdS)�CancelledErrorzThe Future was cancelled.Nrrrrrr0src@seZdZdZdS)�TimeoutErrorz*The operation exceeded the given deadline.Nrrrrrr4src@seZdZdZdS)�InvalidStateErrorz+The operation is not allowed in this state.Nrrrrrr8src@s0eZdZdZdd�Zdd�Zdd�Zdd	�Zd
S)�_Waiterz;Provides the event that wait() and as_completed() block on.cCst��|_g|_dS�N)�	threadingZEvent�event�finished_futures��selfrrr�__init__>s
z_Waiter.__init__cCs|j�|�dSr�r�append�r �futurerrr�
add_resultBsz_Waiter.add_resultcCs|j�|�dSrr"r$rrr�
add_exceptionEsz_Waiter.add_exceptioncCs|j�|�dSrr"r$rrr�
add_cancelledHsz_Waiter.add_cancelledN)rrrrr!r&r'r(rrrrr<s
rcsDeZdZdZ�fdd�Z�fdd�Z�fdd�Z�fdd	�Z�ZS)
�_AsCompletedWaiterzUsed by as_completed().cstt|���t��|_dSr)�superr)r!r�Lock�lockr��	__class__rrr!Nsz_AsCompletedWaiter.__init__c	s0|j� tt|��|�|j��W5QRXdSr)r,r*r)r&r�setr$r-rrr&Rsz_AsCompletedWaiter.add_resultc	s0|j� tt|��|�|j��W5QRXdSr)r,r*r)r'rr/r$r-rrr'Wsz _AsCompletedWaiter.add_exceptionc	s0|j� tt|��|�|j��W5QRXdSr)r,r*r)r(rr/r$r-rrr(\sz _AsCompletedWaiter.add_cancelled)	rrrrr!r&r'r(�
__classcell__rrr-rr)Ks
r)cs8eZdZdZ�fdd�Z�fdd�Z�fdd�Z�ZS)�_FirstCompletedWaiterz*Used by wait(return_when=FIRST_COMPLETED).cst��|�|j��dSr)r*r&rr/r$r-rrr&dsz _FirstCompletedWaiter.add_resultcst��|�|j��dSr)r*r'rr/r$r-rrr'hsz#_FirstCompletedWaiter.add_exceptioncst��|�|j��dSr)r*r(rr/r$r-rrr(lsz#_FirstCompletedWaiter.add_cancelled)rrrrr&r'r(r0rrr-rr1asr1csLeZdZdZ�fdd�Zdd�Z�fdd�Z�fdd	�Z�fd
d�Z�Z	S)�_AllCompletedWaiterz<Used by wait(return_when=FIRST_EXCEPTION and ALL_COMPLETED).cs$||_||_t��|_t���dSr)�num_pending_calls�stop_on_exceptionrr+r,r*r!)r r3r4r-rrr!ss
z_AllCompletedWaiter.__init__c	Cs4|j�$|jd8_|js&|j��W5QRXdS)N�)r,r3rr/rrrr�_decrement_pending_callsysz,_AllCompletedWaiter._decrement_pending_callscst��|�|��dSr)r*r&r6r$r-rrr&sz_AllCompletedWaiter.add_resultcs*t��|�|jr|j��n|��dSr)r*r'r4rr/r6r$r-rrr'�sz!_AllCompletedWaiter.add_exceptioncst��|�|��dSr)r*r(r6r$r-rrr(�sz!_AllCompletedWaiter.add_cancelled)
rrrrr!r6r&r'r(r0rrr-rr2psr2c@s(eZdZdZdd�Zdd�Zdd�ZdS)	�_AcquireFutureszDA context manager that does an ordered acquire of Future conditions.cCst|td�|_dS)N)�key)�sorted�id�futures)r r;rrrr!�sz_AcquireFutures.__init__cCs|jD]}|j��qdSr)r;�
_condition�acquirer$rrr�	__enter__�s
z_AcquireFutures.__enter__cGs|jD]}|j��qdSr)r;r<�release)r �argsr%rrr�__exit__�s
z_AcquireFutures.__exit__N)rrrrr!r>rArrrrr7�sr7cCs�|tkrt�}nZ|tkr t�}nJtdd�|D��}|tkrHt|dd�}n"|tkr^t|dd�}ntd|��|D]}|j	�
|�qn|S)Ncss|]}|jttfkVqdSr��_stater	r
��.0�frrr�	<genexpr>�sz._create_and_install_waiters.<locals>.<genexpr>T)r4FzInvalid return condition: %r)rr)rr1�sumrr2r�
ValueError�_waitersr#)�fs�return_when�waiterZ
pending_countrFrrr�_create_and_install_waiters�s�rNc	csP|rL|d}|D]}|�|�q|j�|j�|�W5QRX~|��VqdS)a~
    Iterate on the list *fs*, yielding finished futures one by one in
    reverse order.
    Before yielding a future, *waiter* is removed from its waiters
    and the future is removed from each set in the collection of sets
    *ref_collect*.

    The aim of this function is to avoid keeping stale references after
    the future is yielded and before the iterator resumes.
    ���N)�remover<rJ�pop)rKrM�ref_collectrFZfutures_setrrr�_yield_finished_futures�srSc	csB|dk	r|t��}t|�}t|�}t|��*tdd�|D��}||}t|t�}W5QRXt|�}z�t|||fd�EdH|�r|dkr�d}n(|t��}|dkr�tdt|�|f��|j
�|�|j�|j}g|_|j
��W5QRX|��t||||fd�EdHq|W5|D]$}|j�|j	�
|�W5QRX�qXdS)anAn iterator over the given futures that yields each as it completes.

    Args:
        fs: The sequence of Futures (possibly created by different Executors) to
            iterate over.
        timeout: The maximum number of seconds to wait. If None, then there
            is no limit on the wait time.

    Returns:
        An iterator that yields the given Futures as they complete (finished or
        cancelled). If any given Futures are duplicated, they will be returned
        once.

    Raises:
        TimeoutError: If the entire result iterator could not be generated
            before the given timeout.
    Ncss |]}|jttfkr|VqdSrrBrDrrrrG�s�zas_completed.<locals>.<genexpr>)rRrz%d (of %d) futures unfinished)�time�	monotonicr/�lenr7rNr�listr<rJrPrSrr�waitr,r�clear�reverse)	rK�timeout�end_timeZ
total_futuresrrrMrFZwait_timeoutrrr�as_completed�sL
�����r]�DoneAndNotDoneFuturesz
done not_donec
Cs
t|���tdd�|D��}t|�|}|tkrJ|rJt||�W5QR�S|tkr~|r~tdd�|D��r~t||�W5QR�St|�t|�kr�t||�W5QR�St||�}W5QRX|j�	|�|D]"}|j
�|j�|�W5QRXq�|�
|j�t|t|�|�S)aWait for the futures in the given sequence to complete.

    Args:
        fs: The sequence of Futures (possibly created by different Executors) to
            wait upon.
        timeout: The maximum number of seconds to wait. If None, then there
            is no limit on the wait time.
        return_when: Indicates when this function should return. The options
            are:

            FIRST_COMPLETED - Return when any future finishes or is
                              cancelled.
            FIRST_EXCEPTION - Return when any future finishes by raising an
                              exception. If no future raises an exception
                              then it is equivalent to ALL_COMPLETED.
            ALL_COMPLETED -   Return when all futures finish or are cancelled.

    Returns:
        A named 2-tuple of sets. The first set, named 'done', contains the
        futures that completed (is finished or cancelled) before the wait
        completed. The second set, named 'not_done', contains uncompleted
        futures.
    css |]}|jttfkr|VqdSrrBrDrrrrG!s�zwait.<locals>.<genexpr>css&|]}|��s|��dk	r|VqdSr)r
�	exceptionrDrrrrG(s�)r7r/rr^r�anyrVrNrrXr<rJrP�updater)rKr[rL�doneZnot_donerMrFrrrrXs"
rXc@s�eZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�Zdd�Zddd�Z
d dd�Zdd�Zdd�Zdd�ZdS)!�Futurez5Represents the result of an asynchronous computation.cCs,t��|_t|_d|_d|_g|_g|_dS)z8Initializes the future. Should not be called by clients.N)	rZ	Conditionr<rrC�_result�
_exceptionrJ�_done_callbacksrrrrr!<s
zFuture.__init__c	Cs>|jD]2}z||�Wqtk
r6t�d|�YqXqdS)N�!exception calling callback for %r)rf�	Exception�LOGGERr_)r �callbackrrr�_invoke_callbacksEs

zFuture._invoke_callbacksc
Cs�|j��|jtkrx|jrHd|jjt|�t|j|jjjfW5QR�Sd|jjt|�t|j|jjjfW5QR�Sd|jjt|�t|jfW5QR�SQRXdS)Nz<%s at %#x state=%s raised %s>z <%s at %#x state=%s returned %s>z<%s at %#x state=%s>)	r<rCr
rer.rr:�_STATE_TO_DESCRIPTION_MAPrdrrrr�__repr__Ls(
���zFuture.__repr__c	Csf|j�N|jttfkr$W5QR�dS|jttfkr@W5QR�dSt|_|j��W5QRX|��dS)z�Cancel the future if possible.

        Returns True if the future was cancelled, False otherwise. A future
        cannot be cancelled if it is running or has already completed.
        FT)r<rCrr
rr	�
notify_allrkrrrr�cancel`sz
Future.cancelc
Cs,|j�|jttfkW5QR�SQRXdS)z(Return True if the future was cancelled.N)r<rCrr	rrrrr
sszFuture.cancelledc
Cs(|j�|jtkW5QR�SQRXdS)z1Return True if the future is currently executing.N)r<rCrrrrrrxszFuture.runningc
Cs.|j�|jtttfkW5QR�SQRXdS)z>Return True of the future was cancelled or finished executing.N)r<rCrr	r
rrrrrb}szFuture.donecCs$|jrz
|j�W5d}Xn|jSdSr)rerdrrrrZ__get_result�s

zFuture.__get_resultc	Csn|j�0|jtttfkr2|j�|�W5QR�dSW5QRXz||�Wn tk
rht�	d|�YnXdS)a%Attaches a callable that will be called when the future finishes.

        Args:
            fn: A callable that will be called with this future as its only
                argument when the future completes or is cancelled. The callable
                will always be called by a thread in the same process in which
                it was added. If the future has already completed or been
                cancelled then the callable will be called immediately. These
                callables are called in the order that they were added.
        Nrg)
r<rCrr	r
rfr#rhrir_)r �fnrrr�add_done_callback�szFuture.add_done_callbackNc
Cs�z�|j��|jttfkr t��n"|jtkrB|��W5QR�W�ZS|j�|�|jttfkrdt��n(|jtkr�|��W5QR�W�St��W5QRXW5d}XdS)aBReturn the result of the call that the future represents.

        Args:
            timeout: The number of seconds to wait for the result if the future
                isn't done. If None, then there is no limit on the wait time.

        Returns:
            The result of the call that the future represents.

        Raises:
            CancelledError: If the future was cancelled.
            TimeoutError: If the future didn't finish executing before the given
                timeout.
            Exception: If the call raised then that exception will be raised.
        N)	r<rCrr	rr
�_Future__get_resultrXr�r r[rrr�result�s

z
Future.resultc
Cs�|j�||jttfkrt��n|jtkr:|jW5QR�S|j�|�|jttfkr\t��n"|jtkrx|jW5QR�St��W5QRXdS)aUReturn the exception raised by the call that the future represents.

        Args:
            timeout: The number of seconds to wait for the exception if the
                future isn't done. If None, then there is no limit on the wait
                time.

        Returns:
            The exception raised by the call that the future represents or None
            if the call completed without raising.

        Raises:
            CancelledError: If the future was cancelled.
            TimeoutError: If the future didn't finish executing before the given
                timeout.
        N)	r<rCrr	rr
rerXrrsrrrr_�s

zFuture.exceptionc	Cs�|j�t|jtkr<t|_|jD]}|�|�qW5QR�dS|jtkrZt|_W5QR�dSt�	dt
|�|j�td��W5QRXdS)a�Mark the future as running or process any cancel notifications.

        Should only be used by Executor implementations and unit tests.

        If the future has been cancelled (cancel() was called and returned
        True) then any threads waiting on the future completing (though calls
        to as_completed() or wait()) are notified and False is returned.

        If the future was not cancelled then it is put in the running state
        (future calls to running() will return True) and True is returned.

        This method should be called by Executor implementations before
        executing the work associated with this future. If this method returns
        False then the work should not be executed.

        Returns:
            False if the Future was cancelled, True otherwise.

        Raises:
            RuntimeError: if this method was already called or if set_result()
                or set_exception() was called.
        FTz!Future %s in unexpected state: %szFuture in unexpected stateN)r<rCrr	rJr(rrriZcriticalr:�RuntimeError)r rMrrr�set_running_or_notify_cancel�s


�z#Future.set_running_or_notify_cancelc	Csl|j�T|jttthkr*td�|j|���||_t|_|jD]}|�	|�q<|j�
�W5QRX|��dS)z�Sets the return value of work associated with the future.

        Should only be used by Executor implementations and unit tests.
        �{}: {!r}N)r<rCrr	r
r�formatrdrJr&rnrk)r rtrMrrr�
set_result
s
zFuture.set_resultc	Csl|j�T|jttthkr*td�|j|���||_t|_|jD]}|�	|�q<|j�
�W5QRX|��dS)z�Sets the result of the future as being the given exception.

        Should only be used by Executor implementations and unit tests.
        rwN)r<rCrr	r
rrxrerJr'rnrk)r r_rMrrr�
set_exceptions
zFuture.set_exception)N)N)rrrrr!rkrmror
rrbrrrqrtr_rvryrzrrrrrc9s	

#
"(rcc@sHeZdZdZdd�Zde_ddd�dd	�Zddd�Zd
d�Zdd�Z	dS)�ExecutorzCThis is an abstract base class for concrete asynchronous executors.cOs\t|�dkrnD|std��n6d|kr>ddl}|jdtdd�ntdt|�d	��t��dS)
a Submits a callable to be executed with the given arguments.

        Schedules the callable to be executed as fn(*args, **kwargs) and returns
        a Future instance representing the execution of the callable.

        Returns:
            A Future representing the given call.
        �z:descriptor 'submit' of 'Executor' object needs an argumentrprNz.Passing 'fn' as keyword argument is deprecated)�
stacklevelz6submit expected at least 1 positional argument, got %dr5)rV�	TypeError�warnings�warn�DeprecationWarning�NotImplementedError)r@�kwargsrrrr�submit.s	
�
�zExecutor.submitz($self, fn, /, *args, **kwargs)Nr5)r[�	chunksizecsB�dk	r�t�����fdd�t|�D�����fdd�}|�S)a}Returns 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: The size of the chunks the iterable will be broken into
                before being passed to a child process. This argument is only
                used by ProcessPoolExecutor; it is ignored by
                ThreadPoolExecutor.

        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.
        Ncsg|]}�j�f|���qSr)r�)rEr@)rpr rr�
<listcomp>`sz Executor.map.<locals>.<listcomp>c	3s\zB����r@�dkr&�����Vq
�����t���Vq
W5�D]}|��qHXdSr)rorZrQrtrTrU)r%)r\rKr[rr�result_iteratordsz%Executor.map.<locals>.result_iterator)rTrU�zip)r rpr[r��	iterablesr�r)r\rprKr r[r�mapGs

zExecutor.mapTcCsdS)a�Clean-up the resources associated with the Executor.

        It is safe to call this method several times. Otherwise, no other
        methods can be called after this one.

        Args:
            wait: If True then shutdown will not return until all running
                futures have finished executing and the resources used by the
                executor have been reclaimed.
        Nr)r rXrrr�shutdownsszExecutor.shutdowncCs|Srrrrrrr>�szExecutor.__enter__cCs|jdd�dS)NT)rXF)r�)r �exc_typeZexc_valZexc_tbrrrrA�szExecutor.__exit__)T)
rrrrr��__text_signature__r�r�r>rArrrrr{+s,

r{c@seZdZdZdS)�BrokenExecutorzR
    Raised when a executor has become non-functional after a severe failure.
    Nrrrrrr��sr�)N)'�
__author__�collectionsZloggingrrTrrrrrrrr	r
Z_FUTURE_STATESrlZ	getLoggerrirhrrrr�objectrr)r1r2r7rNrSr]�
namedtupler^rXrcr{rur�rrrr�<module>sh�	�	

>�1s]PK�j�\1�#znzn
process.pynu�[���# Copyright 2009 Brian Quinlan. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.

"""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"
"""

__author__ = 'Brian Quinlan (brian@sweetapp.com)'

import atexit
import os
from concurrent.futures import _base
import queue
from queue import Full
import multiprocessing as mp
import multiprocessing.connection
from multiprocessing.queues import Queue
import threading
import weakref
from functools import partial
import itertools
import sys
import traceback

# Workers are created as daemon threads and processes. This is done to allow the
# interpreter to exit when there are still idle processes in a
# ProcessPoolExecutor's process pool (i.e. shutdown() was not called). However,
# allowing workers to die with the interpreter has two undesirable properties:
#   - The workers would still be running during interpreter shutdown,
#     meaning that they would fail in unpredictable ways.
#   - The workers could be killed while evaluating a work item, which could
#     be bad if the callable being evaluated has external side-effects e.g.
#     writing to a file.
#
# To work around this problem, an exit handler is installed which tells the
# workers to exit when their work queues are empty and then waits until the
# threads/processes finish.

_threads_wakeups = weakref.WeakKeyDictionary()
_global_shutdown = False


class _ThreadWakeup:
    def __init__(self):
        self._reader, self._writer = mp.Pipe(duplex=False)

    def close(self):
        self._writer.close()
        self._reader.close()

    def wakeup(self):
        self._writer.send_bytes(b"")

    def clear(self):
        while self._reader.poll():
            self._reader.recv_bytes()


def _python_exit():
    global _global_shutdown
    _global_shutdown = True
    items = list(_threads_wakeups.items())
    for _, thread_wakeup in items:
        thread_wakeup.wakeup()
    for t, _ in items:
        t.join()

# Controls how many more calls than processes will be queued in the call queue.
# A smaller number will mean that processes spend more time idle waiting for
# work while a larger number will make Future.cancel() succeed less frequently
# (Futures in the call queue cannot be cancelled).
EXTRA_QUEUED_CALLS = 1


# On Windows, WaitForMultipleObjects is used to wait for processes to finish.
# It can wait on, at most, 63 objects. There is an overhead of two objects:
# - the result queue reader
# - the thread wakeup reader
_MAX_WINDOWS_WORKERS = 63 - 2

# Hack to embed stringification of remote traceback in local traceback

class _RemoteTraceback(Exception):
    def __init__(self, tb):
        self.tb = tb
    def __str__(self):
        return self.tb

class _ExceptionWithTraceback:
    def __init__(self, exc, tb):
        tb = traceback.format_exception(type(exc), exc, tb)
        tb = ''.join(tb)
        self.exc = exc
        self.tb = '\n"""\n%s"""' % tb
    def __reduce__(self):
        return _rebuild_exc, (self.exc, self.tb)

def _rebuild_exc(exc, tb):
    exc.__cause__ = _RemoteTraceback(tb)
    return exc

class _WorkItem(object):
    def __init__(self, future, fn, args, kwargs):
        self.future = future
        self.fn = fn
        self.args = args
        self.kwargs = kwargs

class _ResultItem(object):
    def __init__(self, work_id, exception=None, result=None):
        self.work_id = work_id
        self.exception = exception
        self.result = result

class _CallItem(object):
    def __init__(self, work_id, fn, args, kwargs):
        self.work_id = work_id
        self.fn = fn
        self.args = args
        self.kwargs = kwargs


class _SafeQueue(Queue):
    """Safe Queue set exception to the future object linked to a job"""
    def __init__(self, max_size=0, *, ctx, pending_work_items):
        self.pending_work_items = pending_work_items
        super().__init__(max_size, ctx=ctx)

    def _on_queue_feeder_error(self, e, obj):
        if isinstance(obj, _CallItem):
            tb = traceback.format_exception(type(e), e, e.__traceback__)
            e.__cause__ = _RemoteTraceback('\n"""\n{}"""'.format(''.join(tb)))
            work_item = self.pending_work_items.pop(obj.work_id, None)
            # work_item can be None if another process terminated. In this case,
            # the queue_manager_thread fails all work_items with BrokenProcessPool
            if work_item is not None:
                work_item.future.set_exception(e)
        else:
            super()._on_queue_feeder_error(e, obj)


def _get_chunks(*iterables, chunksize):
    """ Iterates over zip()ed iterables in chunks. """
    it = zip(*iterables)
    while True:
        chunk = tuple(itertools.islice(it, chunksize))
        if not chunk:
            return
        yield chunk

def _process_chunk(fn, chunk):
    """ 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.

    """
    return [fn(*args) for args in chunk]


def _sendback_result(result_queue, work_id, result=None, exception=None):
    """Safely send back the given result or exception"""
    try:
        result_queue.put(_ResultItem(work_id, result=result,
                                     exception=exception))
    except BaseException as e:
        exc = _ExceptionWithTraceback(e, e.__traceback__)
        result_queue.put(_ResultItem(work_id, exception=exc))


def _process_worker(call_queue, result_queue, initializer, initargs):
    """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
    """
    if initializer is not None:
        try:
            initializer(*initargs)
        except BaseException:
            _base.LOGGER.critical('Exception in initializer:', exc_info=True)
            # The parent will notice that the process stopped and
            # mark the pool broken
            return
    while True:
        call_item = call_queue.get(block=True)
        if call_item is None:
            # Wake up queue management thread
            result_queue.put(os.getpid())
            return
        try:
            r = call_item.fn(*call_item.args, **call_item.kwargs)
        except BaseException as e:
            exc = _ExceptionWithTraceback(e, e.__traceback__)
            _sendback_result(result_queue, call_item.work_id, exception=exc)
        else:
            _sendback_result(result_queue, call_item.work_id, result=r)
            del r

        # Liberate the resource as soon as possible, to avoid holding onto
        # open files or shared memory that is not needed anymore
        del call_item


def _add_call_item_to_queue(pending_work_items,
                            work_ids,
                            call_queue):
    """Fills 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.
    """
    while True:
        if call_queue.full():
            return
        try:
            work_id = work_ids.get(block=False)
        except queue.Empty:
            return
        else:
            work_item = pending_work_items[work_id]

            if work_item.future.set_running_or_notify_cancel():
                call_queue.put(_CallItem(work_id,
                                         work_item.fn,
                                         work_item.args,
                                         work_item.kwargs),
                               block=True)
            else:
                del pending_work_items[work_id]
                continue


def _queue_management_worker(executor_reference,
                             processes,
                             pending_work_items,
                             work_ids_queue,
                             call_queue,
                             result_queue,
                             thread_wakeup):
    """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.
    """
    executor = None

    def shutting_down():
        return (_global_shutdown or executor is None
                or executor._shutdown_thread)

    def shutdown_worker():
        # This is an upper bound on the number of children alive.
        n_children_alive = sum(p.is_alive() for p in processes.values())
        n_children_to_stop = n_children_alive
        n_sentinels_sent = 0
        # Send the right number of sentinels, to make sure all children are
        # properly terminated.
        while n_sentinels_sent < n_children_to_stop and n_children_alive > 0:
            for i in range(n_children_to_stop - n_sentinels_sent):
                try:
                    call_queue.put_nowait(None)
                    n_sentinels_sent += 1
                except Full:
                    break
            n_children_alive = sum(p.is_alive() for p in processes.values())

        # Release the queue's resources as soon as possible.
        call_queue.close()
        # If .join() is not called on the created processes then
        # some ctx.Queue methods may deadlock on Mac OS X.
        for p in processes.values():
            p.join()

    result_reader = result_queue._reader
    wakeup_reader = thread_wakeup._reader
    readers = [result_reader, wakeup_reader]

    while True:
        _add_call_item_to_queue(pending_work_items,
                                work_ids_queue,
                                call_queue)

        # Wait for a result to be ready in the result_queue while checking
        # that all worker processes are still running, or for a wake up
        # signal send. The wake up signals come either from new tasks being
        # submitted, from the executor being shutdown/gc-ed, or from the
        # shutdown of the python interpreter.
        worker_sentinels = [p.sentinel for p in processes.values()]
        ready = mp.connection.wait(readers + worker_sentinels)

        cause = None
        is_broken = True
        if result_reader in ready:
            try:
                result_item = result_reader.recv()
                is_broken = False
            except BaseException as e:
                cause = traceback.format_exception(type(e), e, e.__traceback__)

        elif wakeup_reader in ready:
            is_broken = False
            result_item = None
        thread_wakeup.clear()
        if is_broken:
            # Mark the process pool broken so that submits fail right now.
            executor = executor_reference()
            if executor is not None:
                executor._broken = ('A child process terminated '
                                    'abruptly, the process pool is not '
                                    'usable anymore')
                executor._shutdown_thread = True
                executor = None
            bpe = BrokenProcessPool("A process in the process pool was "
                                    "terminated abruptly while the future was "
                                    "running or pending.")
            if cause is not None:
                bpe.__cause__ = _RemoteTraceback(
                    f"\n'''\n{''.join(cause)}'''")
            # All futures in flight must be marked failed
            for work_id, work_item in pending_work_items.items():
                work_item.future.set_exception(bpe)
                # Delete references to object. See issue16284
                del work_item
            pending_work_items.clear()
            # Terminate remaining workers forcibly: the queues or their
            # locks may be in a dirty state and block forever.
            for p in processes.values():
                p.terminate()
            shutdown_worker()
            return
        if isinstance(result_item, int):
            # Clean shutdown of a worker using its PID
            # (avoids marking the executor broken)
            assert shutting_down()
            p = processes.pop(result_item)
            p.join()
            if not processes:
                shutdown_worker()
                return
        elif result_item is not None:
            work_item = pending_work_items.pop(result_item.work_id, None)
            # work_item can be None if another process terminated (see above)
            if work_item is not None:
                if result_item.exception:
                    work_item.future.set_exception(result_item.exception)
                else:
                    work_item.future.set_result(result_item.result)
                # Delete references to object. See issue16284
                del work_item
            # Delete reference to result_item
            del result_item

        # Check whether we should start shutting down.
        executor = executor_reference()
        # No more work items can be added if:
        #   - The interpreter is shutting down OR
        #   - The executor that owns this worker has been collected OR
        #   - The executor that owns this worker has been shutdown.
        if shutting_down():
            try:
                # Flag the executor as shutting down as early as possible if it
                # is not gc-ed yet.
                if executor is not None:
                    executor._shutdown_thread = True
                # Since no new work items can be added, it is safe to shutdown
                # this thread if there are no pending work items.
                if not pending_work_items:
                    shutdown_worker()
                    return
            except Full:
                # This is not a problem: we will eventually be woken up (in
                # result_queue.get()) and be able to send a sentinel again.
                pass
        executor = None


_system_limits_checked = False
_system_limited = None


def _check_system_limits():
    global _system_limits_checked, _system_limited
    if _system_limits_checked:
        if _system_limited:
            raise NotImplementedError(_system_limited)
    _system_limits_checked = True
    try:
        nsems_max = os.sysconf("SC_SEM_NSEMS_MAX")
    except (AttributeError, ValueError):
        # sysconf not available or setting not available
        return
    if nsems_max == -1:
        # indetermined limit, assume that limit is determined
        # by available memory only
        return
    if nsems_max >= 256:
        # minimum number of semaphores available
        # according to POSIX
        return
    _system_limited = ("system provides too few semaphores (%d"
                       " available, 256 necessary)" % nsems_max)
    raise NotImplementedError(_system_limited)


def _chain_from_iterable_of_lists(iterable):
    """
    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.
    """
    for element in iterable:
        element.reverse()
        while element:
            yield element.pop()


class BrokenProcessPool(_base.BrokenExecutor):
    """
    Raised when a process in a ProcessPoolExecutor terminated abruptly
    while a future was in the running state.
    """


class ProcessPoolExecutor(_base.Executor):
    def __init__(self, max_workers=None, mp_context=None,
                 initializer=None, initargs=()):
        """Initializes 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.
        """
        _check_system_limits()

        if max_workers is None:
            self._max_workers = os.cpu_count() or 1
            if sys.platform == 'win32':
                self._max_workers = min(_MAX_WINDOWS_WORKERS,
                                        self._max_workers)
        else:
            if max_workers <= 0:
                raise ValueError("max_workers must be greater than 0")
            elif (sys.platform == 'win32' and
                max_workers > _MAX_WINDOWS_WORKERS):
                raise ValueError(
                    f"max_workers must be <= {_MAX_WINDOWS_WORKERS}")

            self._max_workers = max_workers

        if mp_context is None:
            mp_context = mp.get_context()
        self._mp_context = mp_context

        if initializer is not None and not callable(initializer):
            raise TypeError("initializer must be a callable")
        self._initializer = initializer
        self._initargs = initargs

        # Management thread
        self._queue_management_thread = None

        # Map of pids to processes
        self._processes = {}

        # Shutdown is a two-step process.
        self._shutdown_thread = False
        self._shutdown_lock = threading.Lock()
        self._broken = False
        self._queue_count = 0
        self._pending_work_items = {}

        # Create communication channels for the executor
        # Make the call queue slightly larger than the number of processes to
        # prevent the worker processes from idling. But don't make it too big
        # because futures in the call queue cannot be cancelled.
        queue_size = self._max_workers + EXTRA_QUEUED_CALLS
        self._call_queue = _SafeQueue(
            max_size=queue_size, ctx=self._mp_context,
            pending_work_items=self._pending_work_items)
        # Killed worker processes can produce spurious "broken pipe"
        # tracebacks in the queue's own worker thread. But we detect killed
        # processes anyway, so silence the tracebacks.
        self._call_queue._ignore_epipe = True
        self._result_queue = mp_context.SimpleQueue()
        self._work_ids = queue.Queue()

        # _ThreadWakeup is a communication channel used to interrupt the wait
        # of the main loop of queue_manager_thread from another thread (e.g.
        # when calling executor.submit or executor.shutdown). We do not use the
        # _result_queue to send the wakeup signal to the queue_manager_thread
        # as it could result in a deadlock if a worker process dies with the
        # _result_queue write lock still acquired.
        self._queue_management_thread_wakeup = _ThreadWakeup()

    def _start_queue_management_thread(self):
        if self._queue_management_thread is None:
            # When the executor gets garbarge collected, the weakref callback
            # will wake up the queue management thread so that it can terminate
            # if there is no pending work item.
            def weakref_cb(_,
                           thread_wakeup=self._queue_management_thread_wakeup):
                mp.util.debug('Executor collected: triggering callback for'
                              ' QueueManager wakeup')
                thread_wakeup.wakeup()
            # Start the processes so that their sentinels are known.
            self._adjust_process_count()
            self._queue_management_thread = threading.Thread(
                target=_queue_management_worker,
                args=(weakref.ref(self, weakref_cb),
                      self._processes,
                      self._pending_work_items,
                      self._work_ids,
                      self._call_queue,
                      self._result_queue,
                      self._queue_management_thread_wakeup),
                name="QueueManagerThread")
            self._queue_management_thread.daemon = True
            self._queue_management_thread.start()
            _threads_wakeups[self._queue_management_thread] = \
                self._queue_management_thread_wakeup

    def _adjust_process_count(self):
        for _ in range(len(self._processes), self._max_workers):
            p = self._mp_context.Process(
                target=_process_worker,
                args=(self._call_queue,
                      self._result_queue,
                      self._initializer,
                      self._initargs))
            p.start()
            self._processes[p.pid] = p

    def submit(*args, **kwargs):
        if len(args) >= 2:
            self, fn, *args = args
        elif not args:
            raise TypeError("descriptor 'submit' of 'ProcessPoolExecutor' object "
                            "needs an argument")
        elif 'fn' in kwargs:
            fn = kwargs.pop('fn')
            self, *args = args
            import warnings
            warnings.warn("Passing 'fn' as keyword argument is deprecated",
                          DeprecationWarning, stacklevel=2)
        else:
            raise TypeError('submit expected at least 1 positional argument, '
                            'got %d' % (len(args)-1))

        with self._shutdown_lock:
            if self._broken:
                raise BrokenProcessPool(self._broken)
            if self._shutdown_thread:
                raise RuntimeError('cannot schedule new futures after shutdown')
            if _global_shutdown:
                raise RuntimeError('cannot schedule new futures after '
                                   'interpreter shutdown')

            f = _base.Future()
            w = _WorkItem(f, fn, args, kwargs)

            self._pending_work_items[self._queue_count] = w
            self._work_ids.put(self._queue_count)
            self._queue_count += 1
            # Wake up queue management thread
            self._queue_management_thread_wakeup.wakeup()

            self._start_queue_management_thread()
            return f
    submit.__text_signature__ = _base.Executor.submit.__text_signature__
    submit.__doc__ = _base.Executor.submit.__doc__

    def map(self, fn, *iterables, timeout=None, chunksize=1):
        """Returns 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.
        """
        if chunksize < 1:
            raise ValueError("chunksize must be >= 1.")

        results = super().map(partial(_process_chunk, fn),
                              _get_chunks(*iterables, chunksize=chunksize),
                              timeout=timeout)
        return _chain_from_iterable_of_lists(results)

    def shutdown(self, wait=True):
        with self._shutdown_lock:
            self._shutdown_thread = True
        if self._queue_management_thread:
            # Wake up queue management thread
            self._queue_management_thread_wakeup.wakeup()
            if wait:
                self._queue_management_thread.join()
        # To reduce the risk of opening too many files, remove references to
        # objects that use file descriptors.
        self._queue_management_thread = None
        if self._call_queue is not None:
            self._call_queue.close()
            if wait:
                self._call_queue.join_thread()
            self._call_queue = None
        self._result_queue = None
        self._processes = None

        if self._queue_management_thread_wakeup:
            self._queue_management_thread_wakeup.close()
            self._queue_management_thread_wakeup = None

    shutdown.__doc__ = _base.Executor.shutdown.__doc__

atexit.register(_python_exit)
PK�j�\C�|YY_base.pynu�[���# Copyright 2009 Brian Quinlan. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.

__author__ = 'Brian Quinlan (brian@sweetapp.com)'

import collections
import logging
import threading
import time

FIRST_COMPLETED = 'FIRST_COMPLETED'
FIRST_EXCEPTION = 'FIRST_EXCEPTION'
ALL_COMPLETED = 'ALL_COMPLETED'
_AS_COMPLETED = '_AS_COMPLETED'

# Possible future states (for internal use by the futures package).
PENDING = 'PENDING'
RUNNING = 'RUNNING'
# The future was cancelled by the user...
CANCELLED = 'CANCELLED'
# ...and _Waiter.add_cancelled() was called by a worker.
CANCELLED_AND_NOTIFIED = 'CANCELLED_AND_NOTIFIED'
FINISHED = 'FINISHED'

_FUTURE_STATES = [
    PENDING,
    RUNNING,
    CANCELLED,
    CANCELLED_AND_NOTIFIED,
    FINISHED
]

_STATE_TO_DESCRIPTION_MAP = {
    PENDING: "pending",
    RUNNING: "running",
    CANCELLED: "cancelled",
    CANCELLED_AND_NOTIFIED: "cancelled",
    FINISHED: "finished"
}

# Logger for internal use by the futures package.
LOGGER = logging.getLogger("concurrent.futures")

class Error(Exception):
    """Base class for all future-related exceptions."""
    pass

class CancelledError(Error):
    """The Future was cancelled."""
    pass

class TimeoutError(Error):
    """The operation exceeded the given deadline."""
    pass

class InvalidStateError(Error):
    """The operation is not allowed in this state."""
    pass

class _Waiter(object):
    """Provides the event that wait() and as_completed() block on."""
    def __init__(self):
        self.event = threading.Event()
        self.finished_futures = []

    def add_result(self, future):
        self.finished_futures.append(future)

    def add_exception(self, future):
        self.finished_futures.append(future)

    def add_cancelled(self, future):
        self.finished_futures.append(future)

class _AsCompletedWaiter(_Waiter):
    """Used by as_completed()."""

    def __init__(self):
        super(_AsCompletedWaiter, self).__init__()
        self.lock = threading.Lock()

    def add_result(self, future):
        with self.lock:
            super(_AsCompletedWaiter, self).add_result(future)
            self.event.set()

    def add_exception(self, future):
        with self.lock:
            super(_AsCompletedWaiter, self).add_exception(future)
            self.event.set()

    def add_cancelled(self, future):
        with self.lock:
            super(_AsCompletedWaiter, self).add_cancelled(future)
            self.event.set()

class _FirstCompletedWaiter(_Waiter):
    """Used by wait(return_when=FIRST_COMPLETED)."""

    def add_result(self, future):
        super().add_result(future)
        self.event.set()

    def add_exception(self, future):
        super().add_exception(future)
        self.event.set()

    def add_cancelled(self, future):
        super().add_cancelled(future)
        self.event.set()

class _AllCompletedWaiter(_Waiter):
    """Used by wait(return_when=FIRST_EXCEPTION and ALL_COMPLETED)."""

    def __init__(self, num_pending_calls, stop_on_exception):
        self.num_pending_calls = num_pending_calls
        self.stop_on_exception = stop_on_exception
        self.lock = threading.Lock()
        super().__init__()

    def _decrement_pending_calls(self):
        with self.lock:
            self.num_pending_calls -= 1
            if not self.num_pending_calls:
                self.event.set()

    def add_result(self, future):
        super().add_result(future)
        self._decrement_pending_calls()

    def add_exception(self, future):
        super().add_exception(future)
        if self.stop_on_exception:
            self.event.set()
        else:
            self._decrement_pending_calls()

    def add_cancelled(self, future):
        super().add_cancelled(future)
        self._decrement_pending_calls()

class _AcquireFutures(object):
    """A context manager that does an ordered acquire of Future conditions."""

    def __init__(self, futures):
        self.futures = sorted(futures, key=id)

    def __enter__(self):
        for future in self.futures:
            future._condition.acquire()

    def __exit__(self, *args):
        for future in self.futures:
            future._condition.release()

def _create_and_install_waiters(fs, return_when):
    if return_when == _AS_COMPLETED:
        waiter = _AsCompletedWaiter()
    elif return_when == FIRST_COMPLETED:
        waiter = _FirstCompletedWaiter()
    else:
        pending_count = sum(
                f._state not in [CANCELLED_AND_NOTIFIED, FINISHED] for f in fs)

        if return_when == FIRST_EXCEPTION:
            waiter = _AllCompletedWaiter(pending_count, stop_on_exception=True)
        elif return_when == ALL_COMPLETED:
            waiter = _AllCompletedWaiter(pending_count, stop_on_exception=False)
        else:
            raise ValueError("Invalid return condition: %r" % return_when)

    for f in fs:
        f._waiters.append(waiter)

    return waiter


def _yield_finished_futures(fs, waiter, ref_collect):
    """
    Iterate on the list *fs*, yielding finished futures one by one in
    reverse order.
    Before yielding a future, *waiter* is removed from its waiters
    and the future is removed from each set in the collection of sets
    *ref_collect*.

    The aim of this function is to avoid keeping stale references after
    the future is yielded and before the iterator resumes.
    """
    while fs:
        f = fs[-1]
        for futures_set in ref_collect:
            futures_set.remove(f)
        with f._condition:
            f._waiters.remove(waiter)
        del f
        # Careful not to keep a reference to the popped value
        yield fs.pop()


def as_completed(fs, timeout=None):
    """An iterator over the given futures that yields each as it completes.

    Args:
        fs: The sequence of Futures (possibly created by different Executors) to
            iterate over.
        timeout: The maximum number of seconds to wait. If None, then there
            is no limit on the wait time.

    Returns:
        An iterator that yields the given Futures as they complete (finished or
        cancelled). If any given Futures are duplicated, they will be returned
        once.

    Raises:
        TimeoutError: If the entire result iterator could not be generated
            before the given timeout.
    """
    if timeout is not None:
        end_time = timeout + time.monotonic()

    fs = set(fs)
    total_futures = len(fs)
    with _AcquireFutures(fs):
        finished = set(
                f for f in fs
                if f._state in [CANCELLED_AND_NOTIFIED, FINISHED])
        pending = fs - finished
        waiter = _create_and_install_waiters(fs, _AS_COMPLETED)
    finished = list(finished)
    try:
        yield from _yield_finished_futures(finished, waiter,
                                           ref_collect=(fs,))

        while pending:
            if timeout is None:
                wait_timeout = None
            else:
                wait_timeout = end_time - time.monotonic()
                if wait_timeout < 0:
                    raise TimeoutError(
                            '%d (of %d) futures unfinished' % (
                            len(pending), total_futures))

            waiter.event.wait(wait_timeout)

            with waiter.lock:
                finished = waiter.finished_futures
                waiter.finished_futures = []
                waiter.event.clear()

            # reverse to keep finishing order
            finished.reverse()
            yield from _yield_finished_futures(finished, waiter,
                                               ref_collect=(fs, pending))

    finally:
        # Remove waiter from unfinished futures
        for f in fs:
            with f._condition:
                f._waiters.remove(waiter)

DoneAndNotDoneFutures = collections.namedtuple(
        'DoneAndNotDoneFutures', 'done not_done')
def wait(fs, timeout=None, return_when=ALL_COMPLETED):
    """Wait for the futures in the given sequence to complete.

    Args:
        fs: The sequence of Futures (possibly created by different Executors) to
            wait upon.
        timeout: The maximum number of seconds to wait. If None, then there
            is no limit on the wait time.
        return_when: Indicates when this function should return. The options
            are:

            FIRST_COMPLETED - Return when any future finishes or is
                              cancelled.
            FIRST_EXCEPTION - Return when any future finishes by raising an
                              exception. If no future raises an exception
                              then it is equivalent to ALL_COMPLETED.
            ALL_COMPLETED -   Return when all futures finish or are cancelled.

    Returns:
        A named 2-tuple of sets. The first set, named 'done', contains the
        futures that completed (is finished or cancelled) before the wait
        completed. The second set, named 'not_done', contains uncompleted
        futures.
    """
    with _AcquireFutures(fs):
        done = set(f for f in fs
                   if f._state in [CANCELLED_AND_NOTIFIED, FINISHED])
        not_done = set(fs) - done

        if (return_when == FIRST_COMPLETED) and done:
            return DoneAndNotDoneFutures(done, not_done)
        elif (return_when == FIRST_EXCEPTION) and done:
            if any(f for f in done
                   if not f.cancelled() and f.exception() is not None):
                return DoneAndNotDoneFutures(done, not_done)

        if len(done) == len(fs):
            return DoneAndNotDoneFutures(done, not_done)

        waiter = _create_and_install_waiters(fs, return_when)

    waiter.event.wait(timeout)
    for f in fs:
        with f._condition:
            f._waiters.remove(waiter)

    done.update(waiter.finished_futures)
    return DoneAndNotDoneFutures(done, set(fs) - done)

class Future(object):
    """Represents the result of an asynchronous computation."""

    def __init__(self):
        """Initializes the future. Should not be called by clients."""
        self._condition = threading.Condition()
        self._state = PENDING
        self._result = None
        self._exception = None
        self._waiters = []
        self._done_callbacks = []

    def _invoke_callbacks(self):
        for callback in self._done_callbacks:
            try:
                callback(self)
            except Exception:
                LOGGER.exception('exception calling callback for %r', self)

    def __repr__(self):
        with self._condition:
            if self._state == FINISHED:
                if self._exception:
                    return '<%s at %#x state=%s raised %s>' % (
                        self.__class__.__name__,
                        id(self),
                        _STATE_TO_DESCRIPTION_MAP[self._state],
                        self._exception.__class__.__name__)
                else:
                    return '<%s at %#x state=%s returned %s>' % (
                        self.__class__.__name__,
                        id(self),
                        _STATE_TO_DESCRIPTION_MAP[self._state],
                        self._result.__class__.__name__)
            return '<%s at %#x state=%s>' % (
                    self.__class__.__name__,
                    id(self),
                   _STATE_TO_DESCRIPTION_MAP[self._state])

    def cancel(self):
        """Cancel the future if possible.

        Returns True if the future was cancelled, False otherwise. A future
        cannot be cancelled if it is running or has already completed.
        """
        with self._condition:
            if self._state in [RUNNING, FINISHED]:
                return False

            if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]:
                return True

            self._state = CANCELLED
            self._condition.notify_all()

        self._invoke_callbacks()
        return True

    def cancelled(self):
        """Return True if the future was cancelled."""
        with self._condition:
            return self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]

    def running(self):
        """Return True if the future is currently executing."""
        with self._condition:
            return self._state == RUNNING

    def done(self):
        """Return True of the future was cancelled or finished executing."""
        with self._condition:
            return self._state in [CANCELLED, CANCELLED_AND_NOTIFIED, FINISHED]

    def __get_result(self):
        if self._exception:
            try:
                raise self._exception
            finally:
                # Break a reference cycle with the exception in self._exception
                self = None
        else:
            return self._result

    def add_done_callback(self, fn):
        """Attaches a callable that will be called when the future finishes.

        Args:
            fn: A callable that will be called with this future as its only
                argument when the future completes or is cancelled. The callable
                will always be called by a thread in the same process in which
                it was added. If the future has already completed or been
                cancelled then the callable will be called immediately. These
                callables are called in the order that they were added.
        """
        with self._condition:
            if self._state not in [CANCELLED, CANCELLED_AND_NOTIFIED, FINISHED]:
                self._done_callbacks.append(fn)
                return
        try:
            fn(self)
        except Exception:
            LOGGER.exception('exception calling callback for %r', self)

    def result(self, timeout=None):
        """Return the result of the call that the future represents.

        Args:
            timeout: The number of seconds to wait for the result if the future
                isn't done. If None, then there is no limit on the wait time.

        Returns:
            The result of the call that the future represents.

        Raises:
            CancelledError: If the future was cancelled.
            TimeoutError: If the future didn't finish executing before the given
                timeout.
            Exception: If the call raised then that exception will be raised.
        """
        try:
            with self._condition:
                if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]:
                    raise CancelledError()
                elif self._state == FINISHED:
                    return self.__get_result()

                self._condition.wait(timeout)

                if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]:
                    raise CancelledError()
                elif self._state == FINISHED:
                    return self.__get_result()
                else:
                    raise TimeoutError()
        finally:
            # Break a reference cycle with the exception in self._exception
            self = None

    def exception(self, timeout=None):
        """Return the exception raised by the call that the future represents.

        Args:
            timeout: The number of seconds to wait for the exception if the
                future isn't done. If None, then there is no limit on the wait
                time.

        Returns:
            The exception raised by the call that the future represents or None
            if the call completed without raising.

        Raises:
            CancelledError: If the future was cancelled.
            TimeoutError: If the future didn't finish executing before the given
                timeout.
        """

        with self._condition:
            if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]:
                raise CancelledError()
            elif self._state == FINISHED:
                return self._exception

            self._condition.wait(timeout)

            if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]:
                raise CancelledError()
            elif self._state == FINISHED:
                return self._exception
            else:
                raise TimeoutError()

    # The following methods should only be used by Executors and in tests.
    def set_running_or_notify_cancel(self):
        """Mark the future as running or process any cancel notifications.

        Should only be used by Executor implementations and unit tests.

        If the future has been cancelled (cancel() was called and returned
        True) then any threads waiting on the future completing (though calls
        to as_completed() or wait()) are notified and False is returned.

        If the future was not cancelled then it is put in the running state
        (future calls to running() will return True) and True is returned.

        This method should be called by Executor implementations before
        executing the work associated with this future. If this method returns
        False then the work should not be executed.

        Returns:
            False if the Future was cancelled, True otherwise.

        Raises:
            RuntimeError: if this method was already called or if set_result()
                or set_exception() was called.
        """
        with self._condition:
            if self._state == CANCELLED:
                self._state = CANCELLED_AND_NOTIFIED
                for waiter in self._waiters:
                    waiter.add_cancelled(self)
                # self._condition.notify_all() is not necessary because
                # self.cancel() triggers a notification.
                return False
            elif self._state == PENDING:
                self._state = RUNNING
                return True
            else:
                LOGGER.critical('Future %s in unexpected state: %s',
                                id(self),
                                self._state)
                raise RuntimeError('Future in unexpected state')

    def set_result(self, result):
        """Sets the return value of work associated with the future.

        Should only be used by Executor implementations and unit tests.
        """
        with self._condition:
            if self._state in {CANCELLED, CANCELLED_AND_NOTIFIED, FINISHED}:
                raise InvalidStateError('{}: {!r}'.format(self._state, self))
            self._result = result
            self._state = FINISHED
            for waiter in self._waiters:
                waiter.add_result(self)
            self._condition.notify_all()
        self._invoke_callbacks()

    def set_exception(self, exception):
        """Sets the result of the future as being the given exception.

        Should only be used by Executor implementations and unit tests.
        """
        with self._condition:
            if self._state in {CANCELLED, CANCELLED_AND_NOTIFIED, FINISHED}:
                raise InvalidStateError('{}: {!r}'.format(self._state, self))
            self._exception = exception
            self._state = FINISHED
            for waiter in self._waiters:
                waiter.add_exception(self)
            self._condition.notify_all()
        self._invoke_callbacks()

class Executor(object):
    """This is an abstract base class for concrete asynchronous executors."""

    def submit(*args, **kwargs):
        """Submits a callable to be executed with the given arguments.

        Schedules the callable to be executed as fn(*args, **kwargs) and returns
        a Future instance representing the execution of the callable.

        Returns:
            A Future representing the given call.
        """
        if len(args) >= 2:
            pass
        elif not args:
            raise TypeError("descriptor 'submit' of 'Executor' object "
                            "needs an argument")
        elif 'fn' in kwargs:
            import warnings
            warnings.warn("Passing 'fn' as keyword argument is deprecated",
                          DeprecationWarning, stacklevel=2)
        else:
            raise TypeError('submit expected at least 1 positional argument, '
                            'got %d' % (len(args)-1))

        raise NotImplementedError()
    submit.__text_signature__ = '($self, fn, /, *args, **kwargs)'

    def map(self, fn, *iterables, timeout=None, chunksize=1):
        """Returns 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: The size of the chunks the iterable will be broken into
                before being passed to a child process. This argument is only
                used by ProcessPoolExecutor; it is ignored by
                ThreadPoolExecutor.

        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.
        """
        if timeout is not None:
            end_time = timeout + time.monotonic()

        fs = [self.submit(fn, *args) for args in zip(*iterables)]

        # Yield must be hidden in closure so that the futures are submitted
        # before the first iterator value is required.
        def result_iterator():
            try:
                # reverse to keep finishing order
                fs.reverse()
                while fs:
                    # Careful not to keep a reference to the popped future
                    if timeout is None:
                        yield fs.pop().result()
                    else:
                        yield fs.pop().result(end_time - time.monotonic())
            finally:
                for future in fs:
                    future.cancel()
        return result_iterator()

    def shutdown(self, wait=True):
        """Clean-up the resources associated with the Executor.

        It is safe to call this method several times. Otherwise, no other
        methods can be called after this one.

        Args:
            wait: If True then shutdown will not return until all running
                futures have finished executing and the resources used by the
                executor have been reclaimed.
        """
        pass

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.shutdown(wait=True)
        return False


class BrokenExecutor(RuntimeError):
    """
    Raised when a executor has become non-functional after a severe failure.
    """
PK�j�\Y��?__init__.pynu�[���# Copyright 2009 Brian Quinlan. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.

"""Execute computations asynchronously using threads or processes."""

__author__ = 'Brian Quinlan (brian@sweetapp.com)'

from concurrent.futures._base import (FIRST_COMPLETED,
                                      FIRST_EXCEPTION,
                                      ALL_COMPLETED,
                                      CancelledError,
                                      TimeoutError,
                                      InvalidStateError,
                                      BrokenExecutor,
                                      Future,
                                      Executor,
                                      wait,
                                      as_completed)

__all__ = (
    'FIRST_COMPLETED',
    'FIRST_EXCEPTION',
    'ALL_COMPLETED',
    'CancelledError',
    'TimeoutError',
    'BrokenExecutor',
    'Future',
    'Executor',
    'wait',
    'as_completed',
    'ProcessPoolExecutor',
    'ThreadPoolExecutor',
)


def __dir__():
    return __all__ + ('__author__', '__doc__')


def __getattr__(name):
    global ProcessPoolExecutor, ThreadPoolExecutor

    if name == 'ProcessPoolExecutor':
        from .process import ProcessPoolExecutor as pe
        ProcessPoolExecutor = pe
        return pe

    if name == 'ThreadPoolExecutor':
        from .thread import ThreadPoolExecutor as te
        ThreadPoolExecutor = te
        return te

    raise AttributeError(f"module {__name__} has no attribute {name}")
PK�j�\�Dv�@"@"	thread.pynu�[���# Copyright 2009 Brian Quinlan. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.

"""Implements ThreadPoolExecutor."""

__author__ = 'Brian Quinlan (brian@sweetapp.com)'

import atexit
from concurrent.futures import _base
import itertools
import queue
import threading
import weakref
import os

# Workers are created as daemon threads. This is done to allow the interpreter
# to exit when there are still idle threads in a ThreadPoolExecutor's thread
# pool (i.e. shutdown() was not called). However, allowing workers to die with
# the interpreter has two undesirable properties:
#   - The workers would still be running during interpreter shutdown,
#     meaning that they would fail in unpredictable ways.
#   - The workers could be killed while evaluating a work item, which could
#     be bad if the callable being evaluated has external side-effects e.g.
#     writing to a file.
#
# To work around this problem, an exit handler is installed which tells the
# workers to exit when their work queues are empty and then waits until the
# threads finish.

_threads_queues = weakref.WeakKeyDictionary()
_shutdown = False

def _python_exit():
    global _shutdown
    _shutdown = True
    items = list(_threads_queues.items())
    for t, q in items:
        q.put(None)
    for t, q in items:
        t.join()

atexit.register(_python_exit)


class _WorkItem(object):
    def __init__(self, future, fn, args, kwargs):
        self.future = future
        self.fn = fn
        self.args = args
        self.kwargs = kwargs

    def run(self):
        if not self.future.set_running_or_notify_cancel():
            return

        try:
            result = self.fn(*self.args, **self.kwargs)
        except BaseException as exc:
            self.future.set_exception(exc)
            # Break a reference cycle with the exception 'exc'
            self = None
        else:
            self.future.set_result(result)


def _worker(executor_reference, work_queue, initializer, initargs):
    if initializer is not None:
        try:
            initializer(*initargs)
        except BaseException:
            _base.LOGGER.critical('Exception in initializer:', exc_info=True)
            executor = executor_reference()
            if executor is not None:
                executor._initializer_failed()
            return
    try:
        while True:
            work_item = work_queue.get(block=True)
            if work_item is not None:
                work_item.run()
                # Delete references to object. See issue16284
                del work_item

                # attempt to increment idle count
                executor = executor_reference()
                if executor is not None:
                    executor._idle_semaphore.release()
                del executor
                continue

            executor = executor_reference()
            # Exit if:
            #   - The interpreter is shutting down OR
            #   - The executor that owns the worker has been collected OR
            #   - The executor that owns the worker has been shutdown.
            if _shutdown or executor is None or executor._shutdown:
                # Flag the executor as shutting down as early as possible if it
                # is not gc-ed yet.
                if executor is not None:
                    executor._shutdown = True
                # Notice other workers
                work_queue.put(None)
                return
            del executor
    except BaseException:
        _base.LOGGER.critical('Exception in worker', exc_info=True)


class BrokenThreadPool(_base.BrokenExecutor):
    """
    Raised when a worker thread in a ThreadPoolExecutor failed initializing.
    """


class ThreadPoolExecutor(_base.Executor):

    # Used to assign unique thread names when thread_name_prefix is not supplied.
    _counter = itertools.count().__next__

    def __init__(self, max_workers=None, thread_name_prefix='',
                 initializer=None, initargs=()):
        """Initializes a new ThreadPoolExecutor instance.

        Args:
            max_workers: The maximum number of threads that can be used to
                execute the given calls.
            thread_name_prefix: An optional name prefix to give our threads.
            initializer: A callable used to initialize worker threads.
            initargs: A tuple of arguments to pass to the initializer.
        """
        if max_workers is None:
            # ThreadPoolExecutor is often used to:
            # * CPU bound task which releases GIL
            # * I/O bound task (which releases GIL, of course)
            #
            # We use cpu_count + 4 for both types of tasks.
            # But we limit it to 32 to avoid consuming surprisingly large resource
            # on many core machine.
            max_workers = min(32, (os.cpu_count() or 1) + 4)
        if max_workers <= 0:
            raise ValueError("max_workers must be greater than 0")

        if initializer is not None and not callable(initializer):
            raise TypeError("initializer must be a callable")

        self._max_workers = max_workers
        self._work_queue = queue.SimpleQueue()
        self._idle_semaphore = threading.Semaphore(0)
        self._threads = set()
        self._broken = False
        self._shutdown = False
        self._shutdown_lock = threading.Lock()
        self._thread_name_prefix = (thread_name_prefix or
                                    ("ThreadPoolExecutor-%d" % self._counter()))
        self._initializer = initializer
        self._initargs = initargs

    def submit(*args, **kwargs):
        if len(args) >= 2:
            self, fn, *args = args
        elif not args:
            raise TypeError("descriptor 'submit' of 'ThreadPoolExecutor' object "
                            "needs an argument")
        elif 'fn' in kwargs:
            fn = kwargs.pop('fn')
            self, *args = args
            import warnings
            warnings.warn("Passing 'fn' as keyword argument is deprecated",
                          DeprecationWarning, stacklevel=2)
        else:
            raise TypeError('submit expected at least 1 positional argument, '
                            'got %d' % (len(args)-1))

        with self._shutdown_lock:
            if self._broken:
                raise BrokenThreadPool(self._broken)

            if self._shutdown:
                raise RuntimeError('cannot schedule new futures after shutdown')
            if _shutdown:
                raise RuntimeError('cannot schedule new futures after '
                                   'interpreter shutdown')

            f = _base.Future()
            w = _WorkItem(f, fn, args, kwargs)

            self._work_queue.put(w)
            self._adjust_thread_count()
            return f
    submit.__text_signature__ = _base.Executor.submit.__text_signature__
    submit.__doc__ = _base.Executor.submit.__doc__

    def _adjust_thread_count(self):
        # if idle threads are available, don't spin new threads
        if self._idle_semaphore.acquire(timeout=0):
            return

        # When the executor gets lost, the weakref callback will wake up
        # the worker threads.
        def weakref_cb(_, q=self._work_queue):
            q.put(None)

        num_threads = len(self._threads)
        if num_threads < self._max_workers:
            thread_name = '%s_%d' % (self._thread_name_prefix or self,
                                     num_threads)
            t = threading.Thread(name=thread_name, target=_worker,
                                 args=(weakref.ref(self, weakref_cb),
                                       self._work_queue,
                                       self._initializer,
                                       self._initargs))
            t.daemon = True
            t.start()
            self._threads.add(t)
            _threads_queues[t] = self._work_queue

    def _initializer_failed(self):
        with self._shutdown_lock:
            self._broken = ('A thread initializer failed, the thread pool '
                            'is not usable anymore')
            # Drain work queue and mark pending futures failed
            while True:
                try:
                    work_item = self._work_queue.get_nowait()
                except queue.Empty:
                    break
                if work_item is not None:
                    work_item.future.set_exception(BrokenThreadPool(self._broken))

    def shutdown(self, wait=True):
        with self._shutdown_lock:
            self._shutdown = True
            self._work_queue.put(None)
        if wait:
            for t in self._threads:
                t.join()
    shutdown.__doc__ = _base.Executor.shutdown.__doc__
PK�j�\��x�E5E5(__pycache__/process.cpython-38.opt-2.pycnu�[���PK�j�\�����'�5__pycache__/thread.cpython-38.opt-2.pycnu�[���PK�j�\�Da�NONO"�J__pycache__/process.cpython-38.pycnu�[���PK�j�\(��0O0O(.�__pycache__/process.cpython-38.opt-1.pycnu�[���PK�j�\$��ڶU�U ��__pycache__/_base.cpython-38.pycnu�[���PK�j�\��65��'�?__pycache__/thread.cpython-38.opt-1.pycnu�[���PK�j�\��Q�

)�V__pycache__/__init__.cpython-38.opt-2.pycnu�[���PK�j�\��65��!2[__pycache__/thread.cpython-38.pycnu�[���PK�j�\&B�
Q7Q7&?r__pycache__/_base.cpython-38.opt-2.pycnu�[���PK�j�\,C|VV#�__pycache__/__init__.cpython-38.pycnu�[���PK�j�\,C|VV)��__pycache__/__init__.cpython-38.opt-1.pycnu�[���PK�j�\$��ڶU�U&>�__pycache__/_base.cpython-38.opt-1.pycnu�[���PK�j�\1�#znzn
J	process.pynu�[���PK�j�\C�|YY�w_base.pynu�[���PK�j�\Y��?F�__init__.pynu�[���PK�j�\�Dv�@"@"	��thread.pynu�[���PK��