Ignore:
Timestamp:
Mar 19, 2014, 11:11:30 AM (11 years ago)
Author:
dmik
Message:

python: Update vendor to 2.7.6.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • python/vendor/current/Lib/threading.py

    r2 r388  
    1111import warnings
    1212
    13 from functools import wraps
     13from collections import deque as _deque
    1414from time import time as _time, sleep as _sleep
    1515from traceback import format_exc as _format_exc
    16 from collections import deque
    1716
    1817# Note regarding PEP 8 compliant aliases
     
    6564            if self.__verbose:
    6665                format = format % args
    67                 format = "%s: %s\n" % (
    68                     current_thread().name, format)
     66                # Issue #4188: calling current_thread() can incur an infinite
     67                # recursion if it has to create a DummyThread on the fly.
     68                ident = _get_ident()
     69                try:
     70                    name = _active[ident].name
     71                except KeyError:
     72                    name = "<OS thread %d>" % ident
     73                format = "%s: %s\n" % (name, format)
    6974                _sys.stderr.write(format)
    7075
     
    8388
    8489def setprofile(func):
     90    """Set a profile function for all threads started from the threading module.
     91
     92    The func will be passed to sys.setprofile() for each thread, before its
     93    run() method is called.
     94
     95    """
    8596    global _profile_hook
    8697    _profile_hook = func
    8798
    8899def settrace(func):
     100    """Set a trace function for all threads started from the threading module.
     101
     102    The func will be passed to sys.settrace() for each thread, before its run()
     103    method is called.
     104
     105    """
    89106    global _trace_hook
    90107    _trace_hook = func
     
    95112
    96113def RLock(*args, **kwargs):
     114    """Factory function that returns a new reentrant lock.
     115
     116    A reentrant lock must be released by the thread that acquired it. Once a
     117    thread has acquired a reentrant lock, the same thread may acquire it again
     118    without blocking; the thread must release it once for each time it has
     119    acquired it.
     120
     121    """
    97122    return _RLock(*args, **kwargs)
    98123
    99124class _RLock(_Verbose):
     125    """A reentrant lock must be released by the thread that acquired it. Once a
     126       thread has acquired a reentrant lock, the same thread may acquire it
     127       again without blocking; the thread must release it once for each time it
     128       has acquired it.
     129    """
    100130
    101131    def __init__(self, verbose=None):
     
    115145
    116146    def acquire(self, blocking=1):
     147        """Acquire a lock, blocking or non-blocking.
     148
     149        When invoked without arguments: if this thread already owns the lock,
     150        increment the recursion level by one, and return immediately. Otherwise,
     151        if another thread owns the lock, block until the lock is unlocked. Once
     152        the lock is unlocked (not owned by any thread), then grab ownership, set
     153        the recursion level to one, and return. If more than one thread is
     154        blocked waiting until the lock is unlocked, only one at a time will be
     155        able to grab ownership of the lock. There is no return value in this
     156        case.
     157
     158        When invoked with the blocking argument set to true, do the same thing
     159        as when called without arguments, and return true.
     160
     161        When invoked with the blocking argument set to false, do not block. If a
     162        call without an argument would block, return false immediately;
     163        otherwise, do the same thing as when called without arguments, and
     164        return true.
     165
     166        """
    117167        me = _get_ident()
    118168        if self.__owner == me:
     
    135185
    136186    def release(self):
     187        """Release a lock, decrementing the recursion level.
     188
     189        If after the decrement it is zero, reset the lock to unlocked (not owned
     190        by any thread), and if any other threads are blocked waiting for the
     191        lock to become unlocked, allow exactly one of them to proceed. If after
     192        the decrement the recursion level is still nonzero, the lock remains
     193        locked and owned by the calling thread.
     194
     195        Only call this method when the calling thread owns the lock. A
     196        RuntimeError is raised if this method is called when the lock is
     197        unlocked.
     198
     199        There is no return value.
     200
     201        """
    137202        if self.__owner != _get_ident():
    138203            raise RuntimeError("cannot release un-acquired lock")
     
    175240
    176241def Condition(*args, **kwargs):
     242    """Factory function that returns a new condition variable object.
     243
     244    A condition variable allows one or more threads to wait until they are
     245    notified by another thread.
     246
     247    If the lock argument is given and not None, it must be a Lock or RLock
     248    object, and it is used as the underlying lock. Otherwise, a new RLock object
     249    is created and used as the underlying lock.
     250
     251    """
    177252    return _Condition(*args, **kwargs)
    178253
    179254class _Condition(_Verbose):
     255    """Condition variables allow one or more threads to wait until they are
     256       notified by another thread.
     257    """
    180258
    181259    def __init__(self, lock=None, verbose=None):
     
    229307
    230308    def wait(self, timeout=None):
     309        """Wait until notified or until a timeout occurs.
     310
     311        If the calling thread has not acquired the lock when this method is
     312        called, a RuntimeError is raised.
     313
     314        This method releases the underlying lock, and then blocks until it is
     315        awakened by a notify() or notifyAll() call for the same condition
     316        variable in another thread, or until the optional timeout occurs. Once
     317        awakened or timed out, it re-acquires the lock and returns.
     318
     319        When the timeout argument is present and not None, it should be a
     320        floating point number specifying a timeout for the operation in seconds
     321        (or fractions thereof).
     322
     323        When the underlying lock is an RLock, it is not released using its
     324        release() method, since this may not actually unlock the lock when it
     325        was acquired multiple times recursively. Instead, an internal interface
     326        of the RLock class is used, which really unlocks it even when it has
     327        been recursively acquired several times. Another internal interface is
     328        then used to restore the recursion level when the lock is reacquired.
     329
     330        """
    231331        if not self._is_owned():
    232332            raise RuntimeError("cannot wait on un-acquired lock")
     
    271371
    272372    def notify(self, n=1):
     373        """Wake up one or more threads waiting on this condition, if any.
     374
     375        If the calling thread has not acquired the lock when this method is
     376        called, a RuntimeError is raised.
     377
     378        This method wakes up at most n of the threads waiting for the condition
     379        variable; it is a no-op if no threads are waiting.
     380
     381        """
    273382        if not self._is_owned():
    274383            raise RuntimeError("cannot notify on un-acquired lock")
     
    289398
    290399    def notifyAll(self):
     400        """Wake up all threads waiting on this condition.
     401
     402        If the calling thread has not acquired the lock when this method
     403        is called, a RuntimeError is raised.
     404
     405        """
    291406        self.notify(len(self.__waiters))
    292407
     
    295410
    296411def Semaphore(*args, **kwargs):
     412    """A factory function that returns a new semaphore.
     413
     414    Semaphores manage a counter representing the number of release() calls minus
     415    the number of acquire() calls, plus an initial value. The acquire() method
     416    blocks if necessary until it can return without making the counter
     417    negative. If not given, value defaults to 1.
     418
     419    """
    297420    return _Semaphore(*args, **kwargs)
    298421
    299422class _Semaphore(_Verbose):
     423    """Semaphores manage a counter representing the number of release() calls
     424       minus the number of acquire() calls, plus an initial value. The acquire()
     425       method blocks if necessary until it can return without making the counter
     426       negative. If not given, value defaults to 1.
     427
     428    """
    300429
    301430    # After Tim Peters' semaphore class, but not quite the same (no maximum)
     
    309438
    310439    def acquire(self, blocking=1):
     440        """Acquire a semaphore, decrementing the internal counter by one.
     441
     442        When invoked without arguments: if the internal counter is larger than
     443        zero on entry, decrement it by one and return immediately. If it is zero
     444        on entry, block, waiting until some other thread has called release() to
     445        make it larger than zero. This is done with proper interlocking so that
     446        if multiple acquire() calls are blocked, release() will wake exactly one
     447        of them up. The implementation may pick one at random, so the order in
     448        which blocked threads are awakened should not be relied on. There is no
     449        return value in this case.
     450
     451        When invoked with blocking set to true, do the same thing as when called
     452        without arguments, and return true.
     453
     454        When invoked with blocking set to false, do not block. If a call without
     455        an argument would block, return false immediately; otherwise, do the
     456        same thing as when called without arguments, and return true.
     457
     458        """
    311459        rc = False
    312         self.__cond.acquire()
    313         while self.__value == 0:
    314             if not blocking:
    315                 break
     460        with self.__cond:
     461            while self.__value == 0:
     462                if not blocking:
     463                    break
     464                if __debug__:
     465                    self._note("%s.acquire(%s): blocked waiting, value=%s",
     466                            self, blocking, self.__value)
     467                self.__cond.wait()
     468            else:
     469                self.__value = self.__value - 1
     470                if __debug__:
     471                    self._note("%s.acquire: success, value=%s",
     472                            self, self.__value)
     473                rc = True
     474        return rc
     475
     476    __enter__ = acquire
     477
     478    def release(self):
     479        """Release a semaphore, incrementing the internal counter by one.
     480
     481        When the counter is zero on entry and another thread is waiting for it
     482        to become larger than zero again, wake up that thread.
     483
     484        """
     485        with self.__cond:
     486            self.__value = self.__value + 1
    316487            if __debug__:
    317                 self._note("%s.acquire(%s): blocked waiting, value=%s",
    318                            self, blocking, self.__value)
    319             self.__cond.wait()
    320         else:
    321             self.__value = self.__value - 1
    322             if __debug__:
    323                 self._note("%s.acquire: success, value=%s",
    324                            self, self.__value)
    325             rc = True
    326         self.__cond.release()
    327         return rc
    328 
    329     __enter__ = acquire
    330 
    331     def release(self):
    332         self.__cond.acquire()
    333         self.__value = self.__value + 1
    334         if __debug__:
    335             self._note("%s.release: success, value=%s",
    336                        self, self.__value)
    337         self.__cond.notify()
    338         self.__cond.release()
     488                self._note("%s.release: success, value=%s",
     489                        self, self.__value)
     490            self.__cond.notify()
    339491
    340492    def __exit__(self, t, v, tb):
     
    343495
    344496def BoundedSemaphore(*args, **kwargs):
     497    """A factory function that returns a new bounded semaphore.
     498
     499    A bounded semaphore checks to make sure its current value doesn't exceed its
     500    initial value. If it does, ValueError is raised. In most situations
     501    semaphores are used to guard resources with limited capacity.
     502
     503    If the semaphore is released too many times it's a sign of a bug. If not
     504    given, value defaults to 1.
     505
     506    Like regular semaphores, bounded semaphores manage a counter representing
     507    the number of release() calls minus the number of acquire() calls, plus an
     508    initial value. The acquire() method blocks if necessary until it can return
     509    without making the counter negative. If not given, value defaults to 1.
     510
     511    """
    345512    return _BoundedSemaphore(*args, **kwargs)
    346513
    347514class _BoundedSemaphore(_Semaphore):
    348     """Semaphore that checks that # releases is <= # acquires"""
     515    """A bounded semaphore checks to make sure its current value doesn't exceed
     516       its initial value. If it does, ValueError is raised. In most situations
     517       semaphores are used to guard resources with limited capacity.
     518    """
     519
    349520    def __init__(self, value=1, verbose=None):
    350521        _Semaphore.__init__(self, value, verbose)
     
    352523
    353524    def release(self):
    354         if self._Semaphore__value >= self._initial_value:
    355             raise ValueError, "Semaphore released too many times"
    356         return _Semaphore.release(self)
     525        """Release a semaphore, incrementing the internal counter by one.
     526
     527        When the counter is zero on entry and another thread is waiting for it
     528        to become larger than zero again, wake up that thread.
     529
     530        If the number of releases exceeds the number of acquires,
     531        raise a ValueError.
     532
     533        """
     534        with self._Semaphore__cond:
     535            if self._Semaphore__value >= self._initial_value:
     536                raise ValueError("Semaphore released too many times")
     537            self._Semaphore__value += 1
     538            self._Semaphore__cond.notify()
    357539
    358540
    359541def Event(*args, **kwargs):
     542    """A factory function that returns a new event.
     543
     544    Events manage a flag that can be set to true with the set() method and reset
     545    to false with the clear() method. The wait() method blocks until the flag is
     546    true.
     547
     548    """
    360549    return _Event(*args, **kwargs)
    361550
    362551class _Event(_Verbose):
     552    """A factory function that returns a new event object. An event manages a
     553       flag that can be set to true with the set() method and reset to false
     554       with the clear() method. The wait() method blocks until the flag is true.
     555
     556    """
    363557
    364558    # After Tim Peters' event class (without is_posted())
     
    369563        self.__flag = False
    370564
     565    def _reset_internal_locks(self):
     566        # private!  called by Thread._reset_internal_locks by _after_fork()
     567        self.__cond.__init__()
     568
    371569    def isSet(self):
     570        'Return true if and only if the internal flag is true.'
    372571        return self.__flag
    373572
     
    375574
    376575    def set(self):
     576        """Set the internal flag to true.
     577
     578        All threads waiting for the flag to become true are awakened. Threads
     579        that call wait() once the flag is true will not block at all.
     580
     581        """
    377582        self.__cond.acquire()
    378583        try:
     
    383588
    384589    def clear(self):
     590        """Reset the internal flag to false.
     591
     592        Subsequently, threads calling wait() will block until set() is called to
     593        set the internal flag to true again.
     594
     595        """
    385596        self.__cond.acquire()
    386597        try:
     
    390601
    391602    def wait(self, timeout=None):
     603        """Block until the internal flag is true.
     604
     605        If the internal flag is true on entry, return immediately. Otherwise,
     606        block until another thread calls set() to set the flag to true, or until
     607        the optional timeout occurs.
     608
     609        When the timeout argument is present and not None, it should be a
     610        floating point number specifying a timeout for the operation in seconds
     611        (or fractions thereof).
     612
     613        This method returns the internal flag on exit, so it will always return
     614        True except if a timeout is given and the operation times out.
     615
     616        """
    392617        self.__cond.acquire()
    393618        try:
    394619            if not self.__flag:
    395620                self.__cond.wait(timeout)
     621            return self.__flag
    396622        finally:
    397623            self.__cond.release()
     
    413639
    414640class Thread(_Verbose):
    415 
     641    """A class that represents a thread of control.
     642
     643    This class can be safely subclassed in a limited fashion.
     644
     645    """
    416646    __initialized = False
    417647    # Need to store a reference to sys.exc_info for printing
     
    426656    def __init__(self, group=None, target=None, name=None,
    427657                 args=(), kwargs=None, verbose=None):
     658        """This constructor should always be called with keyword arguments. Arguments are:
     659
     660        *group* should be None; reserved for future extension when a ThreadGroup
     661        class is implemented.
     662
     663        *target* is the callable object to be invoked by the run()
     664        method. Defaults to None, meaning nothing is called.
     665
     666        *name* is the thread name. By default, a unique name is constructed of
     667        the form "Thread-N" where N is a small decimal number.
     668
     669        *args* is the argument tuple for the target invocation. Defaults to ().
     670
     671        *kwargs* is a dictionary of keyword arguments for the target
     672        invocation. Defaults to {}.
     673
     674        If a subclass overrides the constructor, it must make sure to invoke
     675        the base class constructor (Thread.__init__()) before doing anything
     676        else to the thread.
     677
     678"""
    428679        assert group is None, "group argument must be None for now"
    429680        _Verbose.__init__(self, verbose)
     
    444695        self.__stderr = _sys.stderr
    445696
     697    def _reset_internal_locks(self):
     698        # private!  Called by _after_fork() to reset our internal locks as
     699        # they may be in an invalid state leading to a deadlock or crash.
     700        if hasattr(self, '_Thread__block'):  # DummyThread deletes self.__block
     701            self.__block.__init__()
     702        self.__started._reset_internal_locks()
     703
     704    @property
     705    def _block(self):
     706        # used by a unittest
     707        return self.__block
     708
    446709    def _set_daemon(self):
    447710        # Overridden in _MainThread and _DummyThread
     
    462725
    463726    def start(self):
     727        """Start the thread's activity.
     728
     729        It must be called at most once per thread object. It arranges for the
     730        object's run() method to be invoked in a separate thread of control.
     731
     732        This method will raise a RuntimeError if called more than once on the
     733        same thread object.
     734
     735        """
    464736        if not self.__initialized:
    465737            raise RuntimeError("thread.__init__() not called")
    466738        if self.__started.is_set():
    467             raise RuntimeError("thread already started")
     739            raise RuntimeError("threads can only be started once")
    468740        if __debug__:
    469741            self._note("%s.start(): starting thread", self)
    470         _active_limbo_lock.acquire()
    471         _limbo[self] = self
    472         _active_limbo_lock.release()
     742        with _active_limbo_lock:
     743            _limbo[self] = self
    473744        try:
    474745            _start_new_thread(self.__bootstrap, ())
     
    480751
    481752    def run(self):
     753        """Method representing the thread's activity.
     754
     755        You may override this method in a subclass. The standard run() method
     756        invokes the callable object passed to the object's constructor as the
     757        target argument, if any, with sequential and keyword arguments taken
     758        from the args and kwargs arguments, respectively.
     759
     760        """
    482761        try:
    483762            if self.__target:
     
    515794            self._set_ident()
    516795            self.__started.set()
    517             _active_limbo_lock.acquire()
    518             _active[self.__ident] = self
    519             del _limbo[self]
    520             _active_limbo_lock.release()
     796            with _active_limbo_lock:
     797                _active[self.__ident] = self
     798                del _limbo[self]
    521799            if __debug__:
    522800                self._note("%s.__bootstrap(): thread started", self)
     
    587865
    588866    def __stop(self):
     867        # DummyThreads delete self.__block, but they have no waiters to
     868        # notify anyway (join() is forbidden on them).
     869        if not hasattr(self, '_Thread__block'):
     870            return
    589871        self.__block.acquire()
    590872        self.__stopped = True
     
    628910
    629911    def join(self, timeout=None):
     912        """Wait until the thread terminates.
     913
     914        This blocks the calling thread until the thread whose join() method is
     915        called terminates -- either normally or through an unhandled exception
     916        or until the optional timeout occurs.
     917
     918        When the timeout argument is present and not None, it should be a
     919        floating point number specifying a timeout for the operation in seconds
     920        (or fractions thereof). As join() always returns None, you must call
     921        isAlive() after join() to decide whether a timeout happened -- if the
     922        thread is still alive, the join() call timed out.
     923
     924        When the timeout argument is not present or None, the operation will
     925        block until the thread terminates.
     926
     927        A thread can be join()ed many times.
     928
     929        join() raises a RuntimeError if an attempt is made to join the current
     930        thread as that would cause a deadlock. It is also an error to join() a
     931        thread before it has been started and attempts to do so raises the same
     932        exception.
     933
     934        """
    630935        if not self.__initialized:
    631936            raise RuntimeError("Thread.__init__() not called")
     
    662967    @property
    663968    def name(self):
     969        """A string used for identification purposes only.
     970
     971        It has no semantics. Multiple threads may be given the same name. The
     972        initial name is set by the constructor.
     973
     974        """
    664975        assert self.__initialized, "Thread.__init__() not called"
    665976        return self.__name
     
    672983    @property
    673984    def ident(self):
     985        """Thread identifier of this thread or None if it has not been started.
     986
     987        This is a nonzero integer. See the thread.get_ident() function. Thread
     988        identifiers may be recycled when a thread exits and another thread is
     989        created. The identifier is available even after the thread has exited.
     990
     991        """
    674992        assert self.__initialized, "Thread.__init__() not called"
    675993        return self.__ident
    676994
    677995    def isAlive(self):
     996        """Return whether the thread is alive.
     997
     998        This method returns True just before the run() method starts until just
     999        after the run() method terminates. The module function enumerate()
     1000        returns a list of all alive threads.
     1001
     1002        """
    6781003        assert self.__initialized, "Thread.__init__() not called"
    6791004        return self.__started.is_set() and not self.__stopped
     
    6831008    @property
    6841009    def daemon(self):
     1010        """A boolean value indicating whether this thread is a daemon thread (True) or not (False).
     1011
     1012        This must be set before start() is called, otherwise RuntimeError is
     1013        raised. Its initial value is inherited from the creating thread; the
     1014        main thread is not a daemon thread and therefore all threads created in
     1015        the main thread default to daemon = False.
     1016
     1017        The entire Python program exits when no alive non-daemon threads are
     1018        left.
     1019
     1020        """
    6851021        assert self.__initialized, "Thread.__init__() not called"
    6861022        return self.__daemonic
     
    7091045
    7101046def Timer(*args, **kwargs):
     1047    """Factory function to create a Timer object.
     1048
     1049    Timers call a function after a specified number of seconds:
     1050
     1051        t = Timer(30.0, f, args=[], kwargs={})
     1052        t.start()
     1053        t.cancel()     # stop the timer's action if it's still waiting
     1054
     1055    """
    7111056    return _Timer(*args, **kwargs)
    7121057
     
    7141059    """Call a function after a specified number of seconds:
    7151060
    716     t = Timer(30.0, f, args=[], kwargs={})
    717     t.start()
    718     t.cancel() # stop the timer's action if it's still waiting
     1061            t = Timer(30.0, f, args=[], kwargs={})
     1062            t.start()
     1063            t.cancel()     # stop the timer's action if it's still waiting
     1064
    7191065    """
    7201066
     
    7461092        self._Thread__started.set()
    7471093        self._set_ident()
    748         _active_limbo_lock.acquire()
    749         _active[_get_ident()] = self
    750         _active_limbo_lock.release()
     1094        with _active_limbo_lock:
     1095            _active[_get_ident()] = self
    7511096
    7521097    def _set_daemon(self):
     
    7931138        self._Thread__started.set()
    7941139        self._set_ident()
    795         _active_limbo_lock.acquire()
    796         _active[_get_ident()] = self
    797         _active_limbo_lock.release()
     1140        with _active_limbo_lock:
     1141            _active[_get_ident()] = self
    7981142
    7991143    def _set_daemon(self):
     
    8071151
    8081152def currentThread():
     1153    """Return the current Thread object, corresponding to the caller's thread of control.
     1154
     1155    If the caller's thread of control was not created through the threading
     1156    module, a dummy thread object with limited functionality is returned.
     1157
     1158    """
    8091159    try:
    8101160        return _active[_get_ident()]
     
    8161166
    8171167def activeCount():
    818     _active_limbo_lock.acquire()
    819     count = len(_active) + len(_limbo)
    820     _active_limbo_lock.release()
    821     return count
     1168    """Return the number of Thread objects currently alive.
     1169
     1170    The returned count is equal to the length of the list returned by
     1171    enumerate().
     1172
     1173    """
     1174    with _active_limbo_lock:
     1175        return len(_active) + len(_limbo)
    8221176
    8231177active_count = activeCount
     
    8281182
    8291183def enumerate():
    830     _active_limbo_lock.acquire()
    831     active = _active.values() + _limbo.values()
    832     _active_limbo_lock.release()
    833     return active
     1184    """Return a list of all Thread objects currently alive.
     1185
     1186    The list includes daemonic threads, dummy thread objects created by
     1187    current_thread(), and the main thread. It excludes terminated threads and
     1188    threads that have not yet been started.
     1189
     1190    """
     1191    with _active_limbo_lock:
     1192        return _active.values() + _limbo.values()
    8341193
    8351194from thread import stack_size
     
    8641223    current = current_thread()
    8651224    with _active_limbo_lock:
    866         for thread in _active.itervalues():
     1225        for thread in _enumerate():
     1226            # Any lock/condition variable may be currently locked or in an
     1227            # invalid state, so we reinitialize them.
     1228            if hasattr(thread, '_reset_internal_locks'):
     1229                thread._reset_internal_locks()
    8671230            if thread is current:
    8681231                # There is only one active thread. We reset the ident to
     
    8731236            else:
    8741237                # All the others are already stopped.
    875                 # We don't call _Thread__stop() because it tries to acquire
    876                 # thread._Thread__block which could also have been held while
    877                 # we forked.
    878                 thread._Thread__stopped = True
     1238                thread._Thread__stop()
    8791239
    8801240        _limbo.clear()
     
    8961256            self.wc = Condition(self.mon)
    8971257            self.limit = limit
    898             self.queue = deque()
     1258            self.queue = _deque()
    8991259
    9001260        def put(self, item):
Note: See TracChangeset for help on using the changeset viewer.