3 \óRã @sPdZddlZddlZddlZddlZdZdZdZdZdZ dZ d Z d Z d Z e e e e e gZe d e d e de de diZejdƒZGdd„deƒZGdd„deƒZGdd„deƒZGdd„deƒZGdd„deƒZGdd„deƒZGdd„deƒZGdd „d eƒZd!d"„Zd#d$„Zd/d%d&„Zejd'd(ƒZ defd)d*„Z!Gd+d,„d,eƒZ"Gd-d.„d.eƒZ#dS)0z"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.6/concurrent/futures/_base.pyr,src@seZdZdZdS)ÚCancelledErrorzThe Future was cancelled.N)rrrrrrrrr0src@seZdZdZdS)Ú TimeoutErrorz*The operation exceeded the given deadline.N)rrrrrrrrr4src@s0eZdZdZdd„Zdd„Zdd„Zdd „Zd S) Ú_Waiterz;Provides the event that wait() and as_completed() block on.cCstjƒ|_g|_dS)N)Ú threadingZEventÚeventÚfinished_futures)ÚselfrrrÚ__init__:s z_Waiter.__init__cCs|jj|ƒdS)N)rÚappend)rÚfuturerrrÚ add_result>sz_Waiter.add_resultcCs|jj|ƒdS)N)rr)rrrrrÚ add_exceptionAsz_Waiter.add_exceptioncCs|jj|ƒdS)N)rr)rrrrrÚ add_cancelledDsz_Waiter.add_cancelledN)rrrrrr r!r"rrrrr8s rcsDeZdZdZ‡fdd„Z‡fdd„Z‡fdd„Z‡fdd „Z‡ZS) Ú_AsCompletedWaiterzUsed by as_completed().cstt|ƒjƒtjƒ|_dS)N)Úsuperr#rrÚLockÚlock)r)Ú __class__rrrJsz_AsCompletedWaiter.__init__c s0|j� tt|ƒj|ƒ|jjƒWdQRXdS)N)r&r$r#r rÚset)rr)r'rrr Nsz_AsCompletedWaiter.add_resultc s0|j� tt|ƒj|ƒ|jjƒWdQRXdS)N)r&r$r#r!rr()rr)r'rrr!Ssz _AsCompletedWaiter.add_exceptionc s0|j� tt|ƒj|ƒ|jjƒWdQRXdS)N)r&r$r#r"rr()rr)r'rrr"Xsz _AsCompletedWaiter.add_cancelled) rrrrrr r!r"Ú __classcell__rr)r'rr#Gs    r#cs8eZdZdZ‡fdd„Z‡fdd„Z‡fdd„Z‡ZS)Ú_FirstCompletedWaiterz*Used by wait(return_when=FIRST_COMPLETED).cstƒj|ƒ|jjƒdS)N)r$r rr()rr)r'rrr `s z _FirstCompletedWaiter.add_resultcstƒj|ƒ|jjƒdS)N)r$r!rr()rr)r'rrr!ds z#_FirstCompletedWaiter.add_exceptioncstƒj|ƒ|jjƒdS)N)r$r"rr()rr)r'rrr"hs z#_FirstCompletedWaiter.add_cancelled)rrrrr r!r"r)rr)r'rr*]s  r*csLeZdZdZ‡fdd„Zdd„Z‡fdd„Z‡fdd „Z‡fd d „Z‡Z S) Ú_AllCompletedWaiterzŸsz._create_and_install_waiters..T)r-FzInvalid return condition: %r) rr#rr*Úsumrr+rÚ ValueErrorÚ_waitersr)ÚfsÚ return_whenÚwaiterZ pending_countr=rrrÚ_create_and_install_waiters˜s  rEc csXxR|rR|d}x|D]}|j|ƒqW|j�|jj|ƒWdQRX~|jƒVqWdS)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. r.Néÿÿÿÿ)Úremover5rAÚpop)rBrDÚ ref_collectr=Z futures_setrrrÚ_yield_finished_futures®s  rJc csJ|dk r|tjƒ}t|ƒ}t|ƒ}t|ƒ�*tdd„|Dƒƒ}||}t|tƒ}WdQRXt|ƒ}z°t|||fd�EdHx”|�r|dkr’d}n(|tjƒ}|dkrºt dt|ƒ|fƒ‚|j j |ƒ|j �|j }g|_ |j jƒWdQRX|jƒt||||fd�EdHq~WWdx,|D]$}|j�|jj|ƒWdQRX�qWXdS)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 |]}|jttgkr|VqdS)N)r;r r )r<r=rrrr>Ýszas_completed..)rIrz%d (of %d) futures unfinished)ÚtimeÚ monotonicr(Úlenr0rErÚlistrJrrÚwaitr&rÚclearÚreverser5rArG) rBÚtimeoutÚend_timeZ total_futuresrr rDZ wait_timeoutr=rrrÚ as_completedÄs@     rTÚDoneAndNotDoneFuturesz done not_donecCsêt|ƒ�†tdd„|Dƒƒ}t|ƒ|}|tkr>|r>t||ƒS|tkrf|rftdd„|Dƒƒrft||ƒSt|ƒt|ƒkr€t||ƒSt||ƒ}WdQRX|jj |ƒx*|D]"}|j �|j j |ƒWdQRXq¦W|j |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 |]}|jttgkr|VqdS)N)r;r r )r<r=rrrr>szwait..css(|] }|jƒ r|jƒdk r|VqdS)N)r Ú exception)r<r=rrrr>$sN)r0r(rrUrÚanyrMrErrOr5rArGÚupdater)rBrRrCÚdoneZnot_donerDr=rrrrOs"          rOc@s„eZdZdZdd„Zdd„Zdd„Zdd „Zd d „Zd d „Z dd„Z dd„Z dd„Z ddd„Z d dd„Zdd„Zdd„Zdd„ZdS)!ÚFuturez5Represents the result of an asynchronous computation.cCs,tjƒ|_t|_d|_d|_g|_g|_dS)z8Initializes the future. Should not be called by clients.N) rZ Conditionr5rr;Ú_resultÚ _exceptionrAÚ_done_callbacks)rrrrr8s  zFuture.__init__c CsBx<|jD]2}y ||ƒWqtk r8tjd|ƒYqXqWdS)Nz!exception calling callback for %r)r]Ú ExceptionÚLOGGERrV)rÚcallbackrrrÚ_invoke_callbacksAs   zFuture._invoke_callbacksc Cs†|j�v|jtkr`|jrz <%s at %#x state=%s returned %s>z<%s at %#x state=%s>) r5r;r r\r'rr3Ú_STATE_TO_DESCRIPTION_MAPr[)rrrrÚ__repr__Hs" zFuture.__repr__c CsR|j�:|jttgkrdS|jttgkr,dSt|_|jjƒWdQRX|jƒ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. FTN)r5r;rr rr Ú notify_allra)rrrrÚcancel\sz Future.cancelc Cs |j�|jttgkSQRXdS)z(Return True if the future was cancelled.N)r5r;rr )rrrrr oszFuture.cancelledc Cs|j� |jtkSQRXdS)z1Return True if the future is currently executing.N)r5r;r)rrrrr tszFuture.runningc Cs"|j�|jtttgkSQRXdS)z>Return True of the future was cancelled or finished executing.N)r5r;rr r )rrrrrYysz Future.donecCs|jr|j‚n|jSdS)N)r\r[)rrrrZ __get_result~szFuture.__get_resultc Cs>|j�&|jtttgkr(|jj|ƒdSWdQRX||ƒdS)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. N)r5r;rr r r]r)rÚfnrrrÚadd_done_callback„s  zFuture.add_done_callbackNc Csx|j�h|jttgkrtƒ‚n|jtkr0|jƒS|jj|ƒ|jttgkrRtƒ‚n|jtkrd|jƒStƒ‚WdQRXdS)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) r5r;rr rr Ú_Future__get_resultrOr)rrRrrrÚresult•s   z Future.resultc Cst|j�d|jttgkrtƒ‚n|jtkr.|jS|jj|ƒ|jttgkrPtƒ‚n|jtkr`|jStƒ‚WdQRXdS)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) r5r;rr rr r\rOr)rrRrrrrV´s   zFuture.exceptionc Cst|j�d|jtkr6t|_x|jD]}|j|ƒq WdS|jtkrJt|_dStj dt |ƒ|jƒt dƒ‚WdQRXdS)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) r5r;rr rAr"rrr_Zcriticalr3Ú RuntimeError)rrDrrrÚset_running_or_notify_cancelÖs   z#Future.set_running_or_notify_cancelc CsN|j�6||_t|_x|jD]}|j|ƒqW|jjƒWdQRX|jƒdS)z‹Sets the return value of work associated with the future. Should only be used by Executor implementations and unit tests. N)r5r[r r;rAr rdra)rrirDrrrÚ set_resultþs zFuture.set_resultc CsN|j�6||_t|_x|jD]}|j|ƒqW|jjƒWdQRX|jƒdS)z�Sets the result of the future as being the given exception. Should only be used by Executor implementations and unit tests. N)r5r\r r;rAr!rdra)rrVrDrrrÚ set_exception s zFuture.set_exception)N)N)rrrrrrarcrer r rYrhrgrirVrkrlrmrrrrrZ5s   "( rZc@sBeZdZdZdd„Zdddœdd„Zdd d „Zd d „Zdd„ZdS)ÚExecutorzCThis is an abstract base class for concrete asynchronous executors.cOs 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. N)ÚNotImplementedError)rrfr9ÚkwargsrrrÚsubmits zExecutor.submitNr.)rRÚ chunksizecsBˆdk rˆtjƒ‰‡‡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)rq)r<r9)rfrrrú ?sz Executor.map..c 3sdzFˆjƒx8ˆrBˆdkr(ˆjƒjƒVq ˆjƒjˆtjƒƒVq WWdxˆD] }|jƒqNWXdS)N)rQrHrirKrLre)r)rSrBrRrrÚresult_iteratorCs  z%Executor.map..result_iterator)rKrLÚzip)rrfrRrrÚ iterablesrtr)rSrfrBrrRrÚmap&s   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)rrOrrrÚshutdownRs zExecutor.shutdowncCs|S)Nr)rrrrr7_szExecutor.__enter__cCs|jdd�dS)NT)rOF)rx)rÚexc_typeZexc_valZexc_tbrrrr:bs zExecutor.__exit__)T) rrrrrqrwrxr7r:rrrrrns  , rn)N)$Ú __author__Ú collectionsZloggingrrKrrrrrrrr r Z_FUTURE_STATESrbZ getLoggerr_r^rrrÚobjectrr#r*r+r0rErJrTÚ namedtuplerUrOrZrnrrrrÚsR  >1d