h f#@s~dZddlZddlZyddlmZWn"ek rVddlmZYnXddlm Z ddl m Z ddl mZmZyddlmZWn"ek rddlmZYnXd d d d d ddddddddddddgZejZejZejZejZejZy ejZ Wne!k rSdZ YnXej"Z"[da#da$ddZ%ddZ&eZ'ddZGdddZ(e(Z)Gdd d Z*Gd ddZ+Gd!dde+Z,Gd"d d Z-Gd#ddZ.Gd$d%d%e/Z0ej1Z2e2d&d'd(Z3ea4iZ5iZ6e Z7Gd)ddZ8Gd*dde8Z9Gd+d,d,e8Z:Gd-d.d.e8Z;d/d Z<e<Z=d0d Z>e>Z?d1d2Z@d3d ZAdd4lmBZBe:aCd5d6ZDd7d8ZEd9d:ZFydd;lmGZHWn"ek rmdd<lImHZHYnXd=d>ZJdS)?z;Thread module emulating a subset of Java's threading model.N) monotonic)time) format_exc)WeakSet)islicecount)deque active_count Conditioncurrent_thread enumerateEventLockRLock SemaphoreBoundedSemaphoreThreadBarrierTimer ThreadError setprofilesettracelocal stack_sizecCs |adS)zSet a profile function for all threads started from the threading module. The func will be passed to sys.setprofile() for each thread, before its run() method is called. N) _profile_hook)funcr./opt/alt/python34/lib64/python3.4/threading.pyr3scCs |adS)zSet a trace function for all threads started from the threading module. The func will be passed to sys.settrace() for each thread, before its run() method is called. N) _trace_hook)rrrrr=scOs&tdkrt||St||S)a2Factory function that returns a new reentrant lock. A reentrant lock must be released by the thread that acquired it. Once a thread has acquired a reentrant lock, the same thread may acquire it again without blocking; the thread must release it once for each time it has acquired it. N)_CRLock_PyRLock)argskwargsrrrrKs  c@seZdZdZddZddZdddd ZeZd d Zd d Z ddZ ddZ ddZ dS)_RLocka,This class implements reentrant lock objects. A reentrant lock must be released by the thread that acquired it. Once a thread has acquired a reentrant lock, the same thread may acquire it again without blocking; the thread must release it once for each time it has acquired it. cCs"t|_d|_d|_dS)Nr)_allocate_lock_block_owner_count)selfrrr__init__bs  z_RLock.__init__c CsI|j}yt|j}Wntk r.YnXd|jj||jfS)Nz<%s owner=%r count=%d>)r&_activenameKeyError __class____name__r')r(ownerrrr__repr__gs  z_RLock.__repr__TcCs_t}|j|kr+|jd7_dS|jj||}|r[||_d|_n|S)aAcquire a lock, blocking or non-blocking. When invoked without arguments: if this thread already owns the lock, increment the recursion level by one, and return immediately. Otherwise, if another thread owns the lock, block until the lock is unlocked. Once the lock is unlocked (not owned by any thread), then grab ownership, set the recursion level to one, and return. If more than one thread is blocked waiting until the lock is unlocked, only one at a time will be able to grab ownership of the lock. There is no return value in this case. When invoked with the blocking argument set to true, do the same thing as when called without arguments, and return true. When invoked with the blocking argument set to false, do not block. If a call without an argument would block, return false immediately; otherwise, do the same thing as when called without arguments, and return true. When invoked with the floating-point timeout argument set to a positive value, block for at most the number of seconds specified by timeout and as long as the lock cannot be acquired. Return true if the lock has been acquired, false if the timeout has elapsed. r1) get_identr&r'r%acquire)r(blockingtimeoutmercrrrr3ps   z_RLock.acquirecCsX|jtkr!tdn|jd|_}|sTd|_|jjndS)amRelease a lock, decrementing the recursion level. If after the decrement it is zero, reset the lock to unlocked (not owned by any thread), and if any other threads are blocked waiting for the lock to become unlocked, allow exactly one of them to proceed. If after the decrement the recursion level is still nonzero, the lock remains locked and owned by the calling thread. Only call this method when the calling thread owns the lock. A RuntimeError is raised if this method is called when the lock is unlocked. There is no return value. zcannot release un-acquired lockr1N)r&r2 RuntimeErrorr'r%release)r(rrrrr9s  z_RLock.releasecCs|jdS)N)r9)r(tvtbrrr__exit__sz_RLock.__exit__cCs#|jj|\|_|_dS)N)r%r3r'r&)r(staterrr_acquire_restores z_RLock._acquire_restorecCsY|jdkrtdn|j}d|_|j}d|_|jj||fS)Nrzcannot release un-acquired lock)r'r8r&r%r9)r(rr/rrr _release_saves     z_RLock._release_savecCs|jtkS)N)r&r2)r(rrr _is_ownedsz_RLock._is_ownedN) r. __module__ __qualname____doc__r)r0r3 __enter__r9r=r?r@rArrrrr#Xs   $    r#c@seZdZdZdddZddZddZd d Zd d Zd dZ ddZ dddZ dddZ dddZ ddZeZdS)r ajClass that implements a condition variable. A condition variable allows one or more threads to wait until they are notified by another thread. If the lock argument is given and not None, it must be a Lock or RLock object, and it is used as the underlying lock. Otherwise, a new RLock object is created and used as the underlying lock. NcCs|dkrt}n||_|j|_|j|_y|j|_Wntk r]YnXy|j|_Wntk rYnXy|j|_Wntk rYnXt|_ dS)N) r_lockr3r9r@AttributeErrorr?rA_deque_waiters)r(lockrrrr)s$        zCondition.__init__cCs |jjS)N)rGrF)r(rrrrFszCondition.__enter__cGs|jj|S)N)rGr=)r(r!rrrr=szCondition.__exit__cCsd|jt|jfS)Nz)rGlenrJ)r(rrrr0szCondition.__repr__cCs|jjdS)N)rGr9)r(rrrr@szCondition._release_savecCs|jjdS)N)rGr3)r(xrrrr?szCondition._acquire_restorecCs+|jjdr#|jjdSdSdS)NrFT)rGr3r9)r(rrrrAs zCondition._is_ownedcCs|jstdnt}|j|jj||j}d}zW|dkrr|jd}n0|dkr|jd|}n|jd}|SWd|j||sy|jj|Wqt k rYqXnXdS)akWait until notified or until a timeout occurs. If the calling thread has not acquired the lock when this method is called, a RuntimeError is raised. This method releases the underlying lock, and then blocks until it is awakened by a notify() or notify_all() call for the same condition variable in another thread, or until the optional timeout occurs. Once awakened or timed out, it re-acquires the lock and returns. When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof). When the underlying lock is an RLock, it is not released using its release() method, since this may not actually unlock the lock when it was acquired multiple times recursively. Instead, an internal interface of the RLock class is used, which really unlocks it even when it has been recursively acquired several times. Another internal interface is then used to restore the recursion level when the lock is reacquired. zcannot wait on un-acquired lockFNTr) rAr8r$r3rJappendr@r?remove ValueError)r(r5waiterZ saved_stateZgotitrrrwaits*          zCondition.waitcCsd}|}|}xh|s|dk rf|dkrFt|}qf|t}|dkrfPqfn|j||}qW|S)zWait until a condition evaluates to True. predicate should be a callable which result will be interpreted as a boolean value. A timeout may be provided giving the maximum time to wait. Nr)_timerR)r(Z predicater5endtimeZwaittimeresultrrrwait_for2s        zCondition.wait_forr1c Cs|jstdn|j}tt||}|sCdSx>|D]6}|jy|j|WqJtk rYqJXqJWdS)aKWake up one or more threads waiting on this condition, if any. If the calling thread has not acquired the lock when this method is called, a RuntimeError is raised. This method wakes up at most n of the threads waiting for the condition variable; it is a no-op if no threads are waiting. z!cannot notify on un-acquired lockN)rAr8rJrI_islicer9rOrP)r(nZ all_waitersZwaiters_to_notifyrQrrrnotifyIs     zCondition.notifycCs|jt|jdS)zWake up all threads waiting on this condition. If the calling thread has not acquired the lock when this method is called, a RuntimeError is raised. N)rYrLrJ)r(rrr notify_all`szCondition.notify_all)r.rCrDrEr)rFr=r0r@r?rArRrVrYrZZ notifyAllrrrrr s       0 c@sUeZdZdZdddZddddZeZd d Zd d ZdS) raGThis class implements semaphore objects. Semaphores manage a counter representing the number of release() calls minus the number of acquire() calls, plus an initial value. The acquire() method blocks if necessary until it can return without making the counter negative. If not given, value defaults to 1. r1cCs:|dkrtdntt|_||_dS)Nrz$semaphore initial value must be >= 0)rPr r_cond_value)r(valuerrrr)xs zSemaphore.__init__TNc Cs| r"|dk r"tdnd}d}|jx|jdkr|sTPn|dk r|dkr|t|}q|t}|dkrPqn|jj|q;W|jd8_d}WdQX|S)aAcquire a semaphore, decrementing the internal counter by one. When invoked without arguments: if the internal counter is larger than zero on entry, decrement it by one and return immediately. If it is zero on entry, block, waiting until some other thread has called release() to make it larger than zero. This is done with proper interlocking so that if multiple acquire() calls are blocked, release() will wake exactly one of them up. The implementation may pick one at random, so the order in which blocked threads are awakened should not be relied on. There is no return value in this case. When invoked with blocking set to true, do the same thing as when called without arguments, and return true. When invoked with blocking set to false, do not block. If a call without an argument would block, return false immediately; otherwise, do the same thing as when called without arguments, and return true. When invoked with a timeout other than None, it will block for at most timeout seconds. If acquire does not complete successfully in that interval, return false. Return true otherwise. Nz.can't specify timeout for non-blocking acquireFrr1T)rPr[r\rSrR)r(r4r5r7rTrrrr3~s$      zSemaphore.acquirec Cs0|j!|jd7_|jjWdQXdS)zRelease a semaphore, incrementing the internal counter by one. When the counter is zero on entry and another thread is waiting for it to become larger than zero again, wake up that thread. r1N)r[r\rY)r(rrrr9s zSemaphore.releasecCs|jdS)N)r9)r(r:r;r<rrrr=szSemaphore.__exit__) r.rCrDrEr)r3rFr9r=rrrrrls - c@s1eZdZdZdddZddZdS)raImplements a bounded semaphore. A bounded semaphore checks to make sure its current value doesn't exceed its initial value. If it does, ValueError is raised. In most situations semaphores are used to guard resources with limited capacity. If the semaphore is released too many times it's a sign of a bug. If not given, value defaults to 1. Like regular semaphores, bounded semaphores manage a counter representing the number of release() calls minus the number of acquire() calls, plus an initial value. The acquire() method blocks if necessary until it can return without making the counter negative. If not given, value defaults to 1. r1cCstj||||_dS)N)rr)_initial_value)r(r]rrrr)szBoundedSemaphore.__init__c CsQ|jB|j|jkr+tdn|jd7_|jjWdQXdS)a6Release a semaphore, incrementing the internal counter by one. When the counter is zero on entry and another thread is waiting for it to become larger than zero again, wake up that thread. If the number of releases exceeds the number of acquires, raise a ValueError. z!Semaphore released too many timesr1N)r[r\r^rPrY)r(rrrr9s zBoundedSemaphore.releaseN)r.rCrDrEr)r9rrrrrs c@sgeZdZdZddZddZddZeZdd Zd d Z d d dZ d S)r zClass implementing event objects. Events manage a flag that can be set to true with the set() method and reset to false with the clear() method. The wait() method blocks until the flag is true. The flag is initially false. cCstt|_d|_dS)NF)r rr[_flag)r(rrrr)szEvent.__init__cCs|jjtdS)N)r[r)r)r(rrr_reset_internal_locksszEvent._reset_internal_lockscCs|jS)z5Return true if and only if the internal flag is true.)r_)r(rrris_setsz Event.is_setc Cs*|jd|_|jjWdQXdS)zSet the internal flag to true. All threads waiting for it to become true are awakened. Threads that call wait() once the flag is true will not block at all. TN)r[r_rZ)r(rrrsets  z Event.setc Cs|jd|_WdQXdS)zReset the internal flag to false. Subsequently, threads calling wait() will block until set() is called to set the internal flag to true again. FN)r[r_)r(rrrclears z Event.clearNc Cs<|j-|j}|s.|jj|}n|SWdQXdS)aHBlock until the internal flag is true. If the internal flag is true on entry, return immediately. Otherwise, block until another thread calls set() to set the flag to true, or until the optional timeout occurs. When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof). This method returns the internal flag on exit, so it will always return True except if a timeout is given and the operation times out. N)r[r_rR)r(r5ZsignaledrrrrRs   z Event.wait) r.rCrDrEr)r`raZisSetrbrcrRrrrrr s     c@seZdZdZddddZdddZddZd d Zd d Zd dZ ddZ ddZ ddZ e ddZe ddZe ddZdS)rzImplements a Barrier. Useful for synchronizing a fixed number of threads at known synchronization points. Threads block on 'wait()' and are simultaneously once they have all made that call. NcCsCtt|_||_||_||_d|_d|_dS)aWCreate a barrier, initialised to 'parties' threads. 'action' is a callable which, when supplied, will be called by one of the threads after they have all entered the barrier and just prior to releasing them all. If a 'timeout' is provided, it is uses as the default for all subsequent 'wait()' calls. rN)r rr[_action_timeout_parties_stater')r(partiesactionr5rrrr):s     zBarrier.__init__cCs|dkr|j}n|jy|j|j}|jd7_z5|d|jkrg|jn |j||SWd|jd8_|jXWdQXdS)aNWait for the barrier. When the specified number of threads have started waiting, they are all simultaneously awoken. If an 'action' was provided for the barrier, one of the threads will have executed that callback prior to returning. Returns an individual index number from 0 to 'parties-1'. Nr1)rer[_enterr'rf_release_wait_exit)r(r5indexrrrrRJs       z Barrier.waitcCsTx |jdkr"|jjqW|jdkr;tn|jdksPtdS)Nr1rrB)rBr1)rgr[rRBrokenBarrierErrorAssertionError)r(rrrrjhs  zBarrier._enterc CsLy0|jr|jnd|_|jjWn|jYnXdS)Nr1)rdrgr[rZ_break)r(rrrrkss    zBarrier._releasecsejjfdd|s4jtnjdkrLtnjdksatdS)Ncs jdkS)Nr)rgr)r(rrszBarrier._wait..rr1)r[rVrqrorgrp)r(r5r)r(rrls !   z Barrier._waitcCs>|jdkr:|jdkr:d|_|jjq:ndS)Nrr1rB)rBr1)r'rgr[rZ)r(rrrrms z Barrier._exitc Csr|jc|jdkrR|jdkr4d|_q[|jdkr[d|_q[n d|_|jjWdQXdS)zReset the barrier to the initial state. Any threads currently waiting will get the BrokenBarrier exception raised. rr1NrBrB)r[r'rgrZ)r(rrrresets   z Barrier.resetcCs|j|jWdQXdS)zPlace the barrier into a 'broken' state. Useful in case of error. Any currently waiting threads and threads attempting to 'wait()' will have BrokenBarrierError raised. N)r[rq)r(rrraborts z Barrier.abortcCsd|_|jjdS)Nrsrt)rgr[rZ)r(rrrrqs zBarrier._breakcCs|jS)z:Return the number of threads required to trip the barrier.)rf)r(rrrrhszBarrier.partiescCs|jdkr|jSdS)z>Return the number of threads currently waiting at the barrier.r)rgr')r(rrr n_waitingszBarrier.n_waitingcCs |jdkS)z0Return True if the barrier is in a broken state.rsrt)rg)r(rrrbrokenszBarrier.broken)r.rCrDrEr)rRrjrkrlrmrurvrqpropertyrhrwrxrrrrr1s      c@seZdZdS)roN)r.rCrDrrrrros roz Thread-%dcCs |tS)N)_counter)templaterrr_newnamesr|c @seZdZdZdZejZdddfdddddZddZ d d Z d d Z d dZ ddZ ddZddZddZddZddZdddZdd3dd Zed!d"Zejd#d"Zed$d%Zd&d'ZeZed(d)Zejd*d)Zd+d,Zd-d.Zd/d0Zd1d2ZdS)4raA class that represents a thread of control. This class can be safely subclassed in a limited fashion. There are two ways to specify the activity: by passing a callable object to the constructor, or by overriding the run() method in a subclass. FNdaemoncCs|dkstd|dkr-i}n||_t|pEt|_||_||_|dk rx||_ntj |_d|_ d|_ t |_ d|_d|_tj|_tj|dS)aKThis constructor should always be called with keyword arguments. Arguments are: *group* should be None; reserved for future extension when a ThreadGroup class is implemented. *target* is the callable object to be invoked by the run() method. Defaults to None, meaning nothing is called. *name* is the thread name. By default, a unique name is constructed of the form "Thread-N" where N is a small decimal number. *args* is the argument tuple for the target invocation. Defaults to (). *kwargs* is a dictionary of keyword arguments for the target invocation. Defaults to {}. If a subclass overrides the constructor, it must make sure to invoke the base class constructor (Thread.__init__()) before doing anything else to the thread. Nz#group argument must be None for nowFT)rp_targetstrr|_name_args_kwargs _daemonicr r}_ident _tstate_lockr _started _is_stopped _initialized_sysstderr_stderr _danglingadd)r(grouptargetr+r!r"r}rrrr)s"             zThread.__init__cCs6|jj|r |jnd|_d|_dS)NT)rr`_set_tstate_lockrr)r(is_aliverrrr`s    zThread._reset_internal_lockscCs|jstdd}|jjr3d}n|j|jrOd}n|jre|d7}n|jdk r|d|j7}nd|jj |j |fS)Nz Thread.__init__() was not calledinitialZstartedZstoppedz daemonz %sz <%s(%s, %s)>) rrprrarrrrr-r.r)r(Zstatusrrrr0)s      zThread.__repr__cCs|jstdn|jjr6tdnt|t|s                kP&O