\d1Y dZddlZddlZddlZddlZddlZdZdZdZdZ dZ dZ d Z d Z d Ze e e e egZe d e d e de dediZejdZGddeZGddeZeZGddeZGddeZGddeZGddeZGddeZGdd eZd!Zd"Zd.d#Z ej!d$d%Z"defd&Z#d.d'Z$Gd(d)eZ%Gd*d+eZ&Gd,d-e'Z(dS)/z"Brian Quinlan (brian@sweetapp.com)NFIRST_COMPLETEDFIRST_EXCEPTION ALL_COMPLETED _AS_COMPLETEDPENDINGRUNNING CANCELLEDCANCELLED_AND_NOTIFIEDFINISHEDpendingrunning cancelledfinishedzconcurrent.futuresceZdZdZdS)Errorz-Base class for all future-related exceptions.N__name__ __module__ __qualname____doc__)..\python\lib\concurrent\futures\_base.pyrr-s77DrrceZdZdZdS)CancelledErrorzThe Future was cancelled.Nrrrrrr1s##DrrceZdZdZdS)InvalidStateErrorz+The operation is not allowed in this state.Nrrrrrr7s55Drrc*eZdZdZdZdZdZdZdS)_Waiterz;Provides the event that wait() and as_completed() block on.cDtj|_g|_dSN) threadingEventeventfinished_futuresselfs r__init__z_Waiter.__init__=s_&& "rc:|j|dSr!r%appendr'futures r add_resultz_Waiter.add_resultA $$V,,,,,rc:|j|dSr!r*r,s r add_exceptionz_Waiter.add_exceptionDr/rc:|j|dSr!r*r,s r add_cancelledz_Waiter.add_cancelledGr/rN)rrrrr(r.r1r3rrrrr;sVEE###-----------rrc@eZdZdZfdZfdZfdZfdZxZS)_AsCompletedWaiterzUsed by as_completed().ctt|tj|_dSr!)superr5r(r"Locklock)r' __class__s rr(z_AsCompletedWaiter.__init__Ms3  $''00222N$$ rc|j5tt|||jddddS#1swxYwYdSr!)r9r7r5r.r$setr'r-r:s rr.z_AsCompletedWaiter.add_resultQs Y   $d + + 6 6v > > > JNN                     AAAAc|j5tt|||jddddS#1swxYwYdSr!)r9r7r5r1r$r<r=s rr1z _AsCompletedWaiter.add_exceptionV Y   $d + + 9 9& A A A JNN                     r>c|j5tt|||jddddS#1swxYwYdSr!)r9r7r5r3r$r<r=s rr3z _AsCompletedWaiter.add_cancelled[r@r>) rrrrr(r.r1r3 __classcell__r:s@rr5r5Js!!%%%%%  rr5c6eZdZdZfdZfdZfdZxZS)_FirstCompletedWaiterz*Used by wait(return_when=FIRST_COMPLETED).c|t||jdSr!)r7r.r$r<r=s rr.z _FirstCompletedWaiter.add_resultcs3 6""" rc|t||jdSr!)r7r1r$r<r=s rr1z#_FirstCompletedWaiter.add_exceptiong3 f%%% rc|t||jdSr!)r7r3r$r<r=s rr3z#_FirstCompletedWaiter.add_cancelledkrHr)rrrrr.r1r3rBrCs@rrErE`sp44rrEcFeZdZdZfdZdZfdZfdZfdZxZ S)_AllCompletedWaiterz!2!2N$$  rc|j5|xjdzc_|js|jddddS#1swxYwYdS)N)r9rMr$r<r&s r_decrement_pending_callsz,_AllCompletedWaiter._decrement_pending_callsxs Y ! !  " "a ' " ") !     ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !s1AA  A crt||dSr!)r7r.rQr=s rr.z_AllCompletedWaiter.add_result~s3 6""" %%'''''rct||jr|jdS|dSr!)r7r1rNr$r<rQr=s rr1z!_AllCompletedWaiter.add_exceptionsV f%%%  ! , JNN       ) ) + + + + +rcrt||dSr!)r7r3rQr=s rr3z!_AllCompletedWaiter.add_cancelleds3 f%%% %%'''''r) rrrrr(rQr.r1r3rBrCs@rrKrKosFF !!! (((((,,,,,(((((((((rrKc$eZdZdZdZdZdZdS)_AcquireFutureszDA context manager that does an ordered acquire of Future conditions.c<t|t|_dS)N)key)sortedidfutures)r'r[s rr(z_AcquireFutures.__init__sg2... rcL|jD]}|jdSr!)r[ _conditionacquirer,s r __enter__z_AcquireFutures.__enter__5l ( (F   % % ' ' ' ' ( (rcL|jD]}|jdSr!)r[r]release)r'argsr-s r__exit__z_AcquireFutures.__exit__r`rN)rrrrr(r_rdrrrrVrVsGNN///((((((((rrVcv|tkrt}n|tkrt}net d|D}|t krt |d}n/|tkrt |d}ntd|z|D]}|j ||S)Nc3@K|]}|jttfvVdSr!_stater r .0fs r z._create_and_install_waiters..sHPPGH!7 BBPPPPPPrT)rNFzInvalid return condition: %r) rr5rrEsumrrKr ValueError_waitersr+)fs return_whenwaiter pending_countrks r_create_and_install_waitersrtsm###%%  ' '&((PPLNPPPPP  / ) )($OOOFF M ) )(%PPPFF;kIJJ J "" &!!!! Mrc#K|rv|d}|D]}|||j5|j|dddn #1swxYwY~|V|tdSdS)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]ropop)rprr ref_collectrk futures_sets r_yield_finished_futuresr{s  rF& " "K   q ! ! ! ! \ & & J  f % % % & & & & & & & & & & & & & & & ffhh sAAAc #&K||tjz}t|}t|}t |5td|D}||z }t |t }dddn #1swxYwYt|} t|||fEd{V|r|d}n=|tjz }|dkr!tdt||fz|j ||j 5|j }g|_ |j dddn #1swxYwY|t||||fEd{V||D];}|j5|j|dddn #1swxYwY.sECC8 6AAAAAAACCr)ryrz%d (of %d) futures unfinished)time monotonicr<lenrVrtrlistr{ TimeoutErrorr$waitr9r%clearreverser]rorw) rptimeoutend_time total_futuresrr rr wait_timeoutrks r as_completedrs$T^--- RBGGM   @@CCCCCCCx-,R?? @@@@@@@@@@@@@@@ H~~H**8V8:u>>> > > > > > > > J# '$.*:*:: !##&;LL-?99::: L  l + + + % %!2*,' ""$$$ % % % % % % % % % % % % % % %      .x<>=JJJ J J J J J J J' J0 * *A * * !!&))) * * * * * * * * * * * * * * * * * * *A * * !!&))) * * * * * * * * * * * * * * * *sy4BB B #A>G!(E GEGE3GGG G  HH 7 HH H H HDoneAndNotDoneFuturesz done not_donect|}t|5d|D}||z }|tkr|rt||cdddS|tkr7|r5t d|Drt||cdddSt |t |krt||cdddSt||}dddn #1swxYwY|j ||D];}|j 5|j |dddn #1swxYwY<| |jt|||z S)anWait 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. Duplicate futures given to *fs* are removed and will be returned only once. c<h|]}|jttfv|Srrgris r zwait.."s7FFFah#98"DDDDDDrNc3jK|].}|s|*|V/dSr!)r exceptionris rrlzwait..(sPGG++--G,-KKMM,E,E,E,E,EGGr)r<rVrrranyrrtr$rr]rorwupdater%)rprrqdonenot_donerrrks rrrs2 RB   >>FF2FFF9 ? * * *(x88 >>>>>>>> _,,$,GGdGGGGG =,T8<<>>>>>>>> t99B  (x88>>>>>>>>-R==>>>>>>>>>>>>>>>  Lg && \ & & J  f % % % & & & & & & & & & & & & & & & KK'((( rDy 1 11s5.C45C4/C4C44C8;C8$E  E E c |||~S#|wxYw#~wxYwr!)resultcancel)futrs r_result_or_cancelr:sR ::g&& JJLLL C JJLLLL s-AAAA ceZdZdZdZdZdZdZdZdZ dZ d Z d Z dd Z dd ZdZdZdZeejZd S)Futurez5Represents the result of an asynchronous computation.ctj|_t|_d|_d|_g|_g|_dS)z8Initializes the future. Should not be called by clients.N) r" Conditionr]rrh_result _exceptionro_done_callbacksr&s rr(zFuture.__init__Hs<#-//   !rc|jD]9} ||#t$rtd|Y6wxYwdS)N!exception calling callback for %r)r ExceptionLOGGERr)r'callbacks r_invoke_callbackszFuture._invoke_callbacksQss, L LH L L L L  !DdKKKKK L L Ls %??c|j5|jtkr|jrKd|jjt |t|j|jjjfzcdddSd|jjt |t|j|jjjfzcdddSd|jjt |t|jfzcdddS#1swxYwYdS)Nz<%s at %#x state=%s raised %s>z <%s at %#x state=%s returned %s>z<%s at %#x state=%s>) r]rhr rr:rrZ_STATE_TO_DESCRIPTION_MAPrr&s r__repr__zFuture.__repr__Xsh _ ; ;{h&&? 9;/41$+>1: ?<< ; ; ; ; ; ; ; ;>/41$+> .7 A99 ; ; ; ; ; ; ; ;*N+tHH,T[9-;; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;sAC1+>C16.C11C58C5cB|j5|jttfvr ddddS|jtt fvr ddddSt|_|jdddn #1swxYwY|dS)zCancel 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. NFT)r]rhrr r r notify_allrr&s rrz Future.cancells _ ) ){w111 ) ) ) ) ) ) ) ){y*@AAA  ) ) ) ) ) ) ) )$DK O & & ( ( ( ) ) ) ) ) ) ) ) ) ) ) ) ) ) )    tsBB%BBBcn|j5|jttfvcdddS#1swxYwYdS)z(Return True if the future was cancelled.N)r]rhr r r&s rrzFuture.cancelleds _ F F;9.D"EE F F F F F F F F F F F F F F F F F Fs *..cd|j5|jtkcdddS#1swxYwYdS)z1Return True if the future is currently executing.N)r]rhrr&s rr zFuture.runningsx _ * *;') * * * * * * * * * * * * * * * * * *s %))cz|j5|jtttfvcdddS#1swxYwYdS)z>Return True if the future was cancelled or finished executing.N)r]rhr r r r&s rrz Future.dones _ P P;9.Dh"OO P P P P P P P P P P P P P P P P P Ps 044c<|jr |j#d}wxYw|jSr!)rrr&s r __get_resultzFuture.__get_results1 ?  o% < sc<|j5|jtttfvr(|j| ddddS dddn #1swxYwY ||dS#t$rt d|YdSwxYw)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. Nr) r]rhr r r rr+rrr)r'fns radd_done_callbackzFuture.add_done_callbacks_  {9.Dh"OOO$++B///        O                H BtHHHHH H H H   @$ G G G G G G Hs#7AA A% A22%BBNc |j5|jttfvrt |jt kr"|cdddd}S|j||jttfvrt |jt kr"|cdddd}St#1swxYwY d}dS#d}wxYw)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]rhr r rr _Future__get_resultrrr'rs rrz Future.resultsP   ) );9.D"EEE(***[H,,,,.. ) ) ) ) ) ) ) DD$$W---;9.D"EEE(***[H,,,,.. ) ) ) ) ) ) ) DD'..( ) ) ) ) ) ) ) ) ) DDD4DKKKKsBC,AC C,A C? C,CC  C,#C $C,,C0c|j5|jttfvrt |jt kr|jcdddS|j||jttfvrt |jt kr|jcdddSt#1swxYwYdS)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]rhr r rr rrrrs rrzFuture.exceptions$_ % %{y*@AAA$&&&(( % % % % % % % % O  ) ) ){y*@AAA$&&&(( % % % % % % % %#nn$ % % % % % % % % % %s:B=AB=/B==CCc|j5|jtkr9t|_|jD]}|| ddddS|jt krt|_ ddddSt dt||jtd#1swxYwYdS)aMark 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. NFTz!Future %s in unexpected state: %szFuture in unexpected state) r]rhr r ror3rrrcriticalrZ RuntimeError)r'rrs rset_running_or_notify_cancelz#Future.set_running_or_notify_cancelsH._ A A{i''4 "m//F((.... A A A A A A A A''%  A A A A A A A A C "4 $ ---##?@@@ A A A A A A A A A As=B9B9<=B99B=B=c|j5|jttthvr(t d|j|||_t|_|jD]}| ||j dddn #1swxYwY| dS)zSets the return value of work associated with the future. Should only be used by Executor implementations and unit tests. {}: {!r}N) r]rhr r r rformatrror.rr)r'rrrs r set_resultzFuture.set_results _ ) ){y*@(KKK' (9(9$+t(L(LMMM!DL"DK- ( (!!$'''' O & & ( ( ( ) ) ) ) ) ) ) ) ) ) ) ) ) ) )      BB##B'*B'c|j5|jttthvr(t d|j|||_t|_|jD]}| ||j dddn #1swxYwY| dS)zSets the result of the future as being the given exception. Should only be used by Executor implementations and unit tests. rN) r]rhr r r rrrror1rr)r'rrrs r set_exceptionzFuture.set_exception(s _ ) ){y*@(KKK' (9(9$+t(L(LMMM'DO"DK- + +$$T**** O & & ( ( ( ) ) ) ) ) ) ) ) ) ) ) ) ) ) )      rr!)rrrrr(rrrrr rrrrrrrr classmethodtypes GenericAlias__class_getitem__rrrrrEs??"""LLL;;;(&FFF *** PPP    HHH(!!!!F%%%%D&A&A&AP ! ! ! ! ! !$ E$677rrc@eZdZdZdZddddZd dd d Zd Zd ZdS)ExecutorzCThis is an abstract base class for concrete asynchronous executors.ct)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. )NotImplementedError)r'rrckwargss rsubmitzExecutor.submit<s"###rNrP)r chunksizectjzfdt|Dfd}|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. Nc,g|]}jg|RSr)r)rjrcrr's r z Executor.map..`s- A A Akdk"$t$$$ A A Arc3hK r`$tVn8ttjz V`D]}|dS#D]}|wxYwr!)rrrxr~rr)r-rrprs rresult_iteratorz%Executor.map..result_iteratords $ W/999999/(T^EUEU:UVVVVV W!$$FMMOOOO$$b$$FMMOOOO$s A6BB1)r~rzip)r'rrr iterablesrrrps``` @@rmapz Executor.mapGst,  !1!11H A A A A Ai A A A $ $ $ $ $ $ $   rTF)cancel_futurescdS)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. cancel_futures: If True then shutdown will cancel all pending futures. Futures that are completed or running will not be cancelled. Nr)r'rrs rshutdownzExecutor.shutdownss  rc|Sr!rr&s rr_zExecutor.__enter__s rc2|ddS)NT)rF)r)r'exc_typeexc_valexc_tbs rrdzExecutor.__exit__s 4    ur)T) rrrrrrrr_rdrrrrr9sMM $ $ $+/!*!*!*!*!*!X E     rrceZdZdZdS)BrokenExecutorzR Raised when a executor has become non-functional after a severe failure. Nrrrrrrsrrr!)) __author__ collectionsloggingr"r~rrrrrrrr r r _FUTURE_STATESr getLoggerrrrrrrobjectrr5rErKrVrtr{r namedtuplerrrrrrrrrrrs-2  ##      1      Y Y {K j   / 0 0     I        U             - - - - -f - - -,     G   ((((('(((< ( ( ( ( (f ( ( (,,<*<*<*<*|/ .22}02020202fr8r8r8r8r8Vr8r8r8hOOOOOvOOOd\r