Jeremy Hylton | 92bb6e7 | 2002-08-14 19:25:42 +0000 | [diff] [blame] | 1 | """Thread module emulating a subset of Java's threading model.""" |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 2 | |
Fred Drake | a872595 | 2002-12-30 23:32:50 +0000 | [diff] [blame] | 3 | import sys as _sys |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 4 | import _thread |
Fred Drake | a872595 | 2002-12-30 23:32:50 +0000 | [diff] [blame] | 5 | |
Victor Stinner | ec89539 | 2012-04-29 02:41:27 +0200 | [diff] [blame] | 6 | from time import sleep as _sleep |
| 7 | try: |
| 8 | from time import monotonic as _time |
| 9 | except ImportError: |
| 10 | from time import time as _time |
Neil Schemenauer | f607fc5 | 2003-11-05 23:03:00 +0000 | [diff] [blame] | 11 | from traceback import format_exc as _format_exc |
Antoine Pitrou | c081c0c | 2011-07-15 22:12:24 +0200 | [diff] [blame] | 12 | from _weakrefset import WeakSet |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 13 | |
Benjamin Peterson | b3085c9 | 2008-09-01 23:09:31 +0000 | [diff] [blame] | 14 | # Note regarding PEP 8 compliant names |
| 15 | # This threading model was originally inspired by Java, and inherited |
| 16 | # the convention of camelCase function and method names from that |
| 17 | # language. Those originaly names are not in any imminent danger of |
| 18 | # being deprecated (even for Py3k),so this module provides them as an |
| 19 | # alias for the PEP 8 compliant names |
| 20 | # Note that using the new PEP 8 compliant names facilitates substitution |
| 21 | # with the multiprocessing module, which doesn't provide the old |
| 22 | # Java inspired names. |
| 23 | |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 24 | __all__ = ['active_count', 'Condition', 'current_thread', 'enumerate', 'Event', |
Raymond Hettinger | 5cee47f | 2011-01-11 19:59:46 +0000 | [diff] [blame] | 25 | 'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Thread', 'Barrier', |
Benjamin Peterson | 7761b95 | 2011-08-02 13:05:47 -0500 | [diff] [blame] | 26 | 'Timer', 'ThreadError', 'setprofile', 'settrace', 'local', 'stack_size'] |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 27 | |
Raymond Hettinger | 5cee47f | 2011-01-11 19:59:46 +0000 | [diff] [blame] | 28 | # Rename some stuff so "from threading import *" is safe |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 29 | _start_new_thread = _thread.start_new_thread |
| 30 | _allocate_lock = _thread.allocate_lock |
Victor Stinner | 2a12974 | 2011-05-30 23:02:52 +0200 | [diff] [blame] | 31 | get_ident = _thread.get_ident |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 32 | ThreadError = _thread.error |
Antoine Pitrou | 434736a | 2009-11-10 18:46:01 +0000 | [diff] [blame] | 33 | try: |
| 34 | _CRLock = _thread.RLock |
| 35 | except AttributeError: |
| 36 | _CRLock = None |
Antoine Pitrou | 7c3e577 | 2010-04-14 15:44:10 +0000 | [diff] [blame] | 37 | TIMEOUT_MAX = _thread.TIMEOUT_MAX |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 38 | del _thread |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 39 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 40 | |
Jeremy Hylton | bfccb35 | 2003-06-29 16:58:41 +0000 | [diff] [blame] | 41 | # Support for profile and trace hooks |
| 42 | |
| 43 | _profile_hook = None |
| 44 | _trace_hook = None |
| 45 | |
| 46 | def setprofile(func): |
| 47 | global _profile_hook |
| 48 | _profile_hook = func |
Tim Peters | d1b108b | 2003-06-29 17:24:17 +0000 | [diff] [blame] | 49 | |
Jeremy Hylton | bfccb35 | 2003-06-29 16:58:41 +0000 | [diff] [blame] | 50 | def settrace(func): |
| 51 | global _trace_hook |
| 52 | _trace_hook = func |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 53 | |
| 54 | # Synchronization classes |
| 55 | |
| 56 | Lock = _allocate_lock |
| 57 | |
Victor Stinner | 135b6d8 | 2012-03-03 01:32:57 +0100 | [diff] [blame] | 58 | def RLock(*args, **kwargs): |
| 59 | if _CRLock is None: |
| 60 | return _PyRLock(*args, **kwargs) |
Antoine Pitrou | 434736a | 2009-11-10 18:46:01 +0000 | [diff] [blame] | 61 | return _CRLock(*args, **kwargs) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 62 | |
Victor Stinner | 135b6d8 | 2012-03-03 01:32:57 +0100 | [diff] [blame] | 63 | class _RLock: |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 64 | |
Victor Stinner | 135b6d8 | 2012-03-03 01:32:57 +0100 | [diff] [blame] | 65 | def __init__(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 66 | self._block = _allocate_lock() |
| 67 | self._owner = None |
| 68 | self._count = 0 |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 69 | |
| 70 | def __repr__(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 71 | owner = self._owner |
Antoine Pitrou | b087268 | 2009-11-09 16:08:16 +0000 | [diff] [blame] | 72 | try: |
| 73 | owner = _active[owner].name |
| 74 | except KeyError: |
| 75 | pass |
| 76 | return "<%s owner=%r count=%d>" % ( |
| 77 | self.__class__.__name__, owner, self._count) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 78 | |
Antoine Pitrou | 7c3e577 | 2010-04-14 15:44:10 +0000 | [diff] [blame] | 79 | def acquire(self, blocking=True, timeout=-1): |
Victor Stinner | 2a12974 | 2011-05-30 23:02:52 +0200 | [diff] [blame] | 80 | me = get_ident() |
Antoine Pitrou | b087268 | 2009-11-09 16:08:16 +0000 | [diff] [blame] | 81 | if self._owner == me: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 82 | self._count = self._count + 1 |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 83 | return 1 |
Antoine Pitrou | 7c3e577 | 2010-04-14 15:44:10 +0000 | [diff] [blame] | 84 | rc = self._block.acquire(blocking, timeout) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 85 | if rc: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 86 | self._owner = me |
| 87 | self._count = 1 |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 88 | return rc |
| 89 | |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 90 | __enter__ = acquire |
| 91 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 92 | def release(self): |
Victor Stinner | 2a12974 | 2011-05-30 23:02:52 +0200 | [diff] [blame] | 93 | if self._owner != get_ident(): |
Georg Brandl | 495f7b5 | 2009-10-27 15:28:25 +0000 | [diff] [blame] | 94 | raise RuntimeError("cannot release un-acquired lock") |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 95 | self._count = count = self._count - 1 |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 96 | if not count: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 97 | self._owner = None |
| 98 | self._block.release() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 99 | |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 100 | def __exit__(self, t, v, tb): |
| 101 | self.release() |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 102 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 103 | # Internal methods used by condition variables |
| 104 | |
Guido van Rossum | 1bc535d | 2007-05-15 18:46:22 +0000 | [diff] [blame] | 105 | def _acquire_restore(self, state): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 106 | self._block.acquire() |
| 107 | self._count, self._owner = state |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 108 | |
| 109 | def _release_save(self): |
Victor Stinner | c2824d4 | 2011-04-24 23:41:33 +0200 | [diff] [blame] | 110 | if self._count == 0: |
| 111 | raise RuntimeError("cannot release un-acquired lock") |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 112 | count = self._count |
| 113 | self._count = 0 |
| 114 | owner = self._owner |
| 115 | self._owner = None |
| 116 | self._block.release() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 117 | return (count, owner) |
| 118 | |
| 119 | def _is_owned(self): |
Victor Stinner | 2a12974 | 2011-05-30 23:02:52 +0200 | [diff] [blame] | 120 | return self._owner == get_ident() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 121 | |
Antoine Pitrou | 434736a | 2009-11-10 18:46:01 +0000 | [diff] [blame] | 122 | _PyRLock = _RLock |
| 123 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 124 | |
Victor Stinner | 135b6d8 | 2012-03-03 01:32:57 +0100 | [diff] [blame] | 125 | class Condition: |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 126 | |
Victor Stinner | 135b6d8 | 2012-03-03 01:32:57 +0100 | [diff] [blame] | 127 | def __init__(self, lock=None): |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 128 | if lock is None: |
| 129 | lock = RLock() |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 130 | self._lock = lock |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 131 | # Export the lock's acquire() and release() methods |
| 132 | self.acquire = lock.acquire |
| 133 | self.release = lock.release |
| 134 | # If the lock defines _release_save() and/or _acquire_restore(), |
| 135 | # these override the default implementations (which just call |
| 136 | # release() and acquire() on the lock). Ditto for _is_owned(). |
| 137 | try: |
| 138 | self._release_save = lock._release_save |
| 139 | except AttributeError: |
| 140 | pass |
| 141 | try: |
| 142 | self._acquire_restore = lock._acquire_restore |
| 143 | except AttributeError: |
| 144 | pass |
| 145 | try: |
| 146 | self._is_owned = lock._is_owned |
| 147 | except AttributeError: |
| 148 | pass |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 149 | self._waiters = [] |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 150 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 151 | def __enter__(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 152 | return self._lock.__enter__() |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 153 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 154 | def __exit__(self, *args): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 155 | return self._lock.__exit__(*args) |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 156 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 157 | def __repr__(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 158 | return "<Condition(%s, %d)>" % (self._lock, len(self._waiters)) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 159 | |
| 160 | def _release_save(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 161 | self._lock.release() # No state to save |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 162 | |
| 163 | def _acquire_restore(self, x): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 164 | self._lock.acquire() # Ignore saved state |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 165 | |
| 166 | def _is_owned(self): |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 167 | # Return True if lock is owned by current_thread. |
Jeremy Hylton | af7fde7 | 2002-08-14 17:43:59 +0000 | [diff] [blame] | 168 | # This method is called only if __lock doesn't have _is_owned(). |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 169 | if self._lock.acquire(0): |
| 170 | self._lock.release() |
Tim Peters | bc0e910 | 2002-04-04 22:55:58 +0000 | [diff] [blame] | 171 | return False |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 172 | else: |
Tim Peters | bc0e910 | 2002-04-04 22:55:58 +0000 | [diff] [blame] | 173 | return True |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 174 | |
| 175 | def wait(self, timeout=None): |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 176 | if not self._is_owned(): |
Georg Brandl | 495f7b5 | 2009-10-27 15:28:25 +0000 | [diff] [blame] | 177 | raise RuntimeError("cannot wait on un-acquired lock") |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 178 | waiter = _allocate_lock() |
| 179 | waiter.acquire() |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 180 | self._waiters.append(waiter) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 181 | saved_state = self._release_save() |
Tim Peters | c951bf9 | 2001-04-02 20:15:57 +0000 | [diff] [blame] | 182 | try: # restore state no matter what (e.g., KeyboardInterrupt) |
| 183 | if timeout is None: |
| 184 | waiter.acquire() |
Georg Brandl | b9a4391 | 2010-10-28 09:03:20 +0000 | [diff] [blame] | 185 | gotit = True |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 186 | else: |
Antoine Pitrou | 7c3e577 | 2010-04-14 15:44:10 +0000 | [diff] [blame] | 187 | if timeout > 0: |
| 188 | gotit = waiter.acquire(True, timeout) |
| 189 | else: |
| 190 | gotit = waiter.acquire(False) |
Tim Peters | c951bf9 | 2001-04-02 20:15:57 +0000 | [diff] [blame] | 191 | if not gotit: |
Tim Peters | c951bf9 | 2001-04-02 20:15:57 +0000 | [diff] [blame] | 192 | try: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 193 | self._waiters.remove(waiter) |
Tim Peters | c951bf9 | 2001-04-02 20:15:57 +0000 | [diff] [blame] | 194 | except ValueError: |
| 195 | pass |
Georg Brandl | b9a4391 | 2010-10-28 09:03:20 +0000 | [diff] [blame] | 196 | return gotit |
Tim Peters | c951bf9 | 2001-04-02 20:15:57 +0000 | [diff] [blame] | 197 | finally: |
| 198 | self._acquire_restore(saved_state) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 199 | |
Kristján Valur Jónsson | 6331520 | 2010-11-18 12:46:39 +0000 | [diff] [blame] | 200 | def wait_for(self, predicate, timeout=None): |
| 201 | endtime = None |
| 202 | waittime = timeout |
| 203 | result = predicate() |
| 204 | while not result: |
| 205 | if waittime is not None: |
| 206 | if endtime is None: |
| 207 | endtime = _time() + waittime |
| 208 | else: |
| 209 | waittime = endtime - _time() |
| 210 | if waittime <= 0: |
Kristján Valur Jónsson | 6331520 | 2010-11-18 12:46:39 +0000 | [diff] [blame] | 211 | break |
Kristján Valur Jónsson | 6331520 | 2010-11-18 12:46:39 +0000 | [diff] [blame] | 212 | self.wait(waittime) |
| 213 | result = predicate() |
Kristján Valur Jónsson | 6331520 | 2010-11-18 12:46:39 +0000 | [diff] [blame] | 214 | return result |
| 215 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 216 | def notify(self, n=1): |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 217 | if not self._is_owned(): |
Georg Brandl | 495f7b5 | 2009-10-27 15:28:25 +0000 | [diff] [blame] | 218 | raise RuntimeError("cannot notify on un-acquired lock") |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 219 | __waiters = self._waiters |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 220 | waiters = __waiters[:n] |
| 221 | if not waiters: |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 222 | return |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 223 | for waiter in waiters: |
| 224 | waiter.release() |
| 225 | try: |
| 226 | __waiters.remove(waiter) |
| 227 | except ValueError: |
| 228 | pass |
| 229 | |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 230 | def notify_all(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 231 | self.notify(len(self._waiters)) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 232 | |
Benjamin Peterson | b3085c9 | 2008-09-01 23:09:31 +0000 | [diff] [blame] | 233 | notifyAll = notify_all |
| 234 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 235 | |
Victor Stinner | 135b6d8 | 2012-03-03 01:32:57 +0100 | [diff] [blame] | 236 | class Semaphore: |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 237 | |
Andrew M. Kuchling | 39d3bfc | 2000-02-29 00:10:24 +0000 | [diff] [blame] | 238 | # After Tim Peters' semaphore class, but not quite the same (no maximum) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 239 | |
Victor Stinner | 135b6d8 | 2012-03-03 01:32:57 +0100 | [diff] [blame] | 240 | def __init__(self, value=1): |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 241 | if value < 0: |
| 242 | raise ValueError("semaphore initial value must be >= 0") |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 243 | self._cond = Condition(Lock()) |
| 244 | self._value = value |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 245 | |
Antoine Pitrou | 0454af9 | 2010-04-17 23:51:58 +0000 | [diff] [blame] | 246 | def acquire(self, blocking=True, timeout=None): |
| 247 | if not blocking and timeout is not None: |
| 248 | raise ValueError("can't specify timeout for non-blocking acquire") |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 249 | rc = False |
Antoine Pitrou | 0454af9 | 2010-04-17 23:51:58 +0000 | [diff] [blame] | 250 | endtime = None |
Serhiy Storchaka | 81a5855 | 2013-04-22 22:51:43 +0300 | [diff] [blame^] | 251 | with self._cond: |
| 252 | while self._value == 0: |
| 253 | if not blocking: |
| 254 | break |
| 255 | if timeout is not None: |
| 256 | if endtime is None: |
| 257 | endtime = _time() + timeout |
| 258 | else: |
| 259 | timeout = endtime - _time() |
| 260 | if timeout <= 0: |
| 261 | break |
| 262 | self._cond.wait(timeout) |
| 263 | else: |
| 264 | self._value = self._value - 1 |
| 265 | rc = True |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 266 | return rc |
| 267 | |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 268 | __enter__ = acquire |
| 269 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 270 | def release(self): |
Serhiy Storchaka | 81a5855 | 2013-04-22 22:51:43 +0300 | [diff] [blame^] | 271 | with self._cond: |
| 272 | self._value = self._value + 1 |
| 273 | self._cond.notify() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 274 | |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 275 | def __exit__(self, t, v, tb): |
| 276 | self.release() |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 277 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 278 | |
Éric Araujo | 0cdd445 | 2011-07-28 00:28:28 +0200 | [diff] [blame] | 279 | class BoundedSemaphore(Semaphore): |
Skip Montanaro | e428bb7 | 2001-08-20 20:27:58 +0000 | [diff] [blame] | 280 | """Semaphore that checks that # releases is <= # acquires""" |
Victor Stinner | 135b6d8 | 2012-03-03 01:32:57 +0100 | [diff] [blame] | 281 | def __init__(self, value=1): |
| 282 | Semaphore.__init__(self, value) |
Skip Montanaro | e428bb7 | 2001-08-20 20:27:58 +0000 | [diff] [blame] | 283 | self._initial_value = value |
| 284 | |
| 285 | def release(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 286 | if self._value >= self._initial_value: |
Collin Winter | ce36ad8 | 2007-08-30 01:19:48 +0000 | [diff] [blame] | 287 | raise ValueError("Semaphore released too many times") |
Éric Araujo | 0cdd445 | 2011-07-28 00:28:28 +0200 | [diff] [blame] | 288 | return Semaphore.release(self) |
Skip Montanaro | e428bb7 | 2001-08-20 20:27:58 +0000 | [diff] [blame] | 289 | |
| 290 | |
Victor Stinner | 135b6d8 | 2012-03-03 01:32:57 +0100 | [diff] [blame] | 291 | class Event: |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 292 | |
| 293 | # After Tim Peters' event class (without is_posted()) |
| 294 | |
Victor Stinner | 135b6d8 | 2012-03-03 01:32:57 +0100 | [diff] [blame] | 295 | def __init__(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 296 | self._cond = Condition(Lock()) |
| 297 | self._flag = False |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 298 | |
Gregory P. Smith | 9bd4a24 | 2011-01-04 18:33:38 +0000 | [diff] [blame] | 299 | def _reset_internal_locks(self): |
| 300 | # private! called by Thread._reset_internal_locks by _after_fork() |
| 301 | self._cond.__init__() |
| 302 | |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 303 | def is_set(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 304 | return self._flag |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 305 | |
Benjamin Peterson | b3085c9 | 2008-09-01 23:09:31 +0000 | [diff] [blame] | 306 | isSet = is_set |
Benjamin Peterson | f0923f5 | 2008-08-18 22:10:13 +0000 | [diff] [blame] | 307 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 308 | def set(self): |
Christian Heimes | 969fe57 | 2008-01-25 11:23:10 +0000 | [diff] [blame] | 309 | self._cond.acquire() |
| 310 | try: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 311 | self._flag = True |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 312 | self._cond.notify_all() |
Christian Heimes | 969fe57 | 2008-01-25 11:23:10 +0000 | [diff] [blame] | 313 | finally: |
| 314 | self._cond.release() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 315 | |
| 316 | def clear(self): |
Christian Heimes | 969fe57 | 2008-01-25 11:23:10 +0000 | [diff] [blame] | 317 | self._cond.acquire() |
| 318 | try: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 319 | self._flag = False |
Christian Heimes | 969fe57 | 2008-01-25 11:23:10 +0000 | [diff] [blame] | 320 | finally: |
| 321 | self._cond.release() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 322 | |
| 323 | def wait(self, timeout=None): |
Christian Heimes | 969fe57 | 2008-01-25 11:23:10 +0000 | [diff] [blame] | 324 | self._cond.acquire() |
| 325 | try: |
Charles-François Natali | ded0348 | 2012-01-07 18:24:56 +0100 | [diff] [blame] | 326 | signaled = self._flag |
| 327 | if not signaled: |
| 328 | signaled = self._cond.wait(timeout) |
| 329 | return signaled |
Christian Heimes | 969fe57 | 2008-01-25 11:23:10 +0000 | [diff] [blame] | 330 | finally: |
| 331 | self._cond.release() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 332 | |
Kristján Valur Jónsson | 3be0003 | 2010-10-28 09:43:10 +0000 | [diff] [blame] | 333 | |
| 334 | # A barrier class. Inspired in part by the pthread_barrier_* api and |
| 335 | # the CyclicBarrier class from Java. See |
| 336 | # http://sourceware.org/pthreads-win32/manual/pthread_barrier_init.html and |
| 337 | # http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/ |
| 338 | # CyclicBarrier.html |
| 339 | # for information. |
| 340 | # We maintain two main states, 'filling' and 'draining' enabling the barrier |
| 341 | # to be cyclic. Threads are not allowed into it until it has fully drained |
| 342 | # since the previous cycle. In addition, a 'resetting' state exists which is |
| 343 | # similar to 'draining' except that threads leave with a BrokenBarrierError, |
Ezio Melotti | e130a52 | 2011-10-19 10:58:56 +0300 | [diff] [blame] | 344 | # and a 'broken' state in which all threads get the exception. |
Victor Stinner | 135b6d8 | 2012-03-03 01:32:57 +0100 | [diff] [blame] | 345 | class Barrier: |
Kristján Valur Jónsson | 3be0003 | 2010-10-28 09:43:10 +0000 | [diff] [blame] | 346 | """ |
| 347 | Barrier. Useful for synchronizing a fixed number of threads |
| 348 | at known synchronization points. Threads block on 'wait()' and are |
| 349 | simultaneously once they have all made that call. |
| 350 | """ |
Victor Stinner | 135b6d8 | 2012-03-03 01:32:57 +0100 | [diff] [blame] | 351 | def __init__(self, parties, action=None, timeout=None): |
Kristján Valur Jónsson | 3be0003 | 2010-10-28 09:43:10 +0000 | [diff] [blame] | 352 | """ |
| 353 | Create a barrier, initialised to 'parties' threads. |
| 354 | 'action' is a callable which, when supplied, will be called |
| 355 | by one of the threads after they have all entered the |
| 356 | barrier and just prior to releasing them all. |
| 357 | If a 'timeout' is provided, it is uses as the default for |
| 358 | all subsequent 'wait()' calls. |
| 359 | """ |
Kristján Valur Jónsson | 3be0003 | 2010-10-28 09:43:10 +0000 | [diff] [blame] | 360 | self._cond = Condition(Lock()) |
| 361 | self._action = action |
| 362 | self._timeout = timeout |
| 363 | self._parties = parties |
| 364 | self._state = 0 #0 filling, 1, draining, -1 resetting, -2 broken |
| 365 | self._count = 0 |
| 366 | |
| 367 | def wait(self, timeout=None): |
| 368 | """ |
| 369 | Wait for the barrier. When the specified number of threads have |
| 370 | started waiting, they are all simultaneously awoken. If an 'action' |
| 371 | was provided for the barrier, one of the threads will have executed |
| 372 | that callback prior to returning. |
| 373 | Returns an individual index number from 0 to 'parties-1'. |
| 374 | """ |
| 375 | if timeout is None: |
| 376 | timeout = self._timeout |
| 377 | with self._cond: |
| 378 | self._enter() # Block while the barrier drains. |
| 379 | index = self._count |
| 380 | self._count += 1 |
| 381 | try: |
| 382 | if index + 1 == self._parties: |
| 383 | # We release the barrier |
| 384 | self._release() |
| 385 | else: |
| 386 | # We wait until someone releases us |
| 387 | self._wait(timeout) |
| 388 | return index |
| 389 | finally: |
| 390 | self._count -= 1 |
| 391 | # Wake up any threads waiting for barrier to drain. |
| 392 | self._exit() |
| 393 | |
| 394 | # Block until the barrier is ready for us, or raise an exception |
| 395 | # if it is broken. |
| 396 | def _enter(self): |
| 397 | while self._state in (-1, 1): |
| 398 | # It is draining or resetting, wait until done |
| 399 | self._cond.wait() |
| 400 | #see if the barrier is in a broken state |
| 401 | if self._state < 0: |
| 402 | raise BrokenBarrierError |
| 403 | assert self._state == 0 |
| 404 | |
| 405 | # Optionally run the 'action' and release the threads waiting |
| 406 | # in the barrier. |
| 407 | def _release(self): |
| 408 | try: |
| 409 | if self._action: |
| 410 | self._action() |
| 411 | # enter draining state |
| 412 | self._state = 1 |
| 413 | self._cond.notify_all() |
| 414 | except: |
| 415 | #an exception during the _action handler. Break and reraise |
| 416 | self._break() |
| 417 | raise |
| 418 | |
| 419 | # Wait in the barrier until we are relased. Raise an exception |
| 420 | # if the barrier is reset or broken. |
| 421 | def _wait(self, timeout): |
Kristján Valur Jónsson | 6331520 | 2010-11-18 12:46:39 +0000 | [diff] [blame] | 422 | if not self._cond.wait_for(lambda : self._state != 0, timeout): |
| 423 | #timed out. Break the barrier |
| 424 | self._break() |
| 425 | raise BrokenBarrierError |
| 426 | if self._state < 0: |
| 427 | raise BrokenBarrierError |
Kristján Valur Jónsson | 3be0003 | 2010-10-28 09:43:10 +0000 | [diff] [blame] | 428 | assert self._state == 1 |
| 429 | |
| 430 | # If we are the last thread to exit the barrier, signal any threads |
| 431 | # waiting for the barrier to drain. |
| 432 | def _exit(self): |
| 433 | if self._count == 0: |
| 434 | if self._state in (-1, 1): |
| 435 | #resetting or draining |
| 436 | self._state = 0 |
| 437 | self._cond.notify_all() |
| 438 | |
| 439 | def reset(self): |
| 440 | """ |
| 441 | Reset the barrier to the initial state. |
| 442 | Any threads currently waiting will get the BrokenBarrier exception |
| 443 | raised. |
| 444 | """ |
| 445 | with self._cond: |
| 446 | if self._count > 0: |
| 447 | if self._state == 0: |
| 448 | #reset the barrier, waking up threads |
| 449 | self._state = -1 |
| 450 | elif self._state == -2: |
| 451 | #was broken, set it to reset state |
| 452 | #which clears when the last thread exits |
| 453 | self._state = -1 |
| 454 | else: |
| 455 | self._state = 0 |
| 456 | self._cond.notify_all() |
| 457 | |
| 458 | def abort(self): |
| 459 | """ |
| 460 | Place the barrier into a 'broken' state. |
| 461 | Useful in case of error. Any currently waiting threads and |
| 462 | threads attempting to 'wait()' will have BrokenBarrierError |
| 463 | raised. |
| 464 | """ |
| 465 | with self._cond: |
| 466 | self._break() |
| 467 | |
| 468 | def _break(self): |
| 469 | # An internal error was detected. The barrier is set to |
| 470 | # a broken state all parties awakened. |
| 471 | self._state = -2 |
| 472 | self._cond.notify_all() |
| 473 | |
| 474 | @property |
| 475 | def parties(self): |
| 476 | """ |
| 477 | Return the number of threads required to trip the barrier. |
| 478 | """ |
| 479 | return self._parties |
| 480 | |
| 481 | @property |
| 482 | def n_waiting(self): |
| 483 | """ |
| 484 | Return the number of threads that are currently waiting at the barrier. |
| 485 | """ |
| 486 | # We don't need synchronization here since this is an ephemeral result |
| 487 | # anyway. It returns the correct value in the steady state. |
| 488 | if self._state == 0: |
| 489 | return self._count |
| 490 | return 0 |
| 491 | |
| 492 | @property |
| 493 | def broken(self): |
| 494 | """ |
| 495 | Return True if the barrier is in a broken state |
| 496 | """ |
| 497 | return self._state == -2 |
| 498 | |
| 499 | #exception raised by the Barrier class |
| 500 | class BrokenBarrierError(RuntimeError): pass |
| 501 | |
| 502 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 503 | # Helper to generate new thread names |
| 504 | _counter = 0 |
| 505 | def _newname(template="Thread-%d"): |
| 506 | global _counter |
| 507 | _counter = _counter + 1 |
| 508 | return template % _counter |
| 509 | |
| 510 | # Active thread administration |
| 511 | _active_limbo_lock = _allocate_lock() |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 512 | _active = {} # maps thread id to Thread object |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 513 | _limbo = {} |
| 514 | |
Antoine Pitrou | c081c0c | 2011-07-15 22:12:24 +0200 | [diff] [blame] | 515 | # For debug and leak testing |
| 516 | _dangling = WeakSet() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 517 | |
| 518 | # Main class for threads |
| 519 | |
Victor Stinner | 135b6d8 | 2012-03-03 01:32:57 +0100 | [diff] [blame] | 520 | class Thread: |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 521 | |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 522 | __initialized = False |
Brett Cannon | cc4e935 | 2004-07-03 03:52:35 +0000 | [diff] [blame] | 523 | # Need to store a reference to sys.exc_info for printing |
| 524 | # out exceptions when a thread tries to use a global var. during interp. |
| 525 | # shutdown and thus raises an exception about trying to perform some |
| 526 | # operation on/with a NoneType |
| 527 | __exc_info = _sys.exc_info |
Christian Heimes | bbe741d | 2008-03-28 10:53:29 +0000 | [diff] [blame] | 528 | # Keep sys.exc_clear too to clear the exception just before |
| 529 | # allowing .join() to return. |
| 530 | #XXX __exc_clear = _sys.exc_clear |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 531 | |
| 532 | def __init__(self, group=None, target=None, name=None, |
Victor Stinner | 135b6d8 | 2012-03-03 01:32:57 +0100 | [diff] [blame] | 533 | args=(), kwargs=None, *, daemon=None): |
Guido van Rossum | 5a43e1a | 1998-06-09 19:04:26 +0000 | [diff] [blame] | 534 | assert group is None, "group argument must be None for now" |
Georg Brandl | a4a8b82 | 2005-07-15 09:13:21 +0000 | [diff] [blame] | 535 | if kwargs is None: |
| 536 | kwargs = {} |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 537 | self._target = target |
| 538 | self._name = str(name or _newname()) |
| 539 | self._args = args |
| 540 | self._kwargs = kwargs |
Antoine Pitrou | 0bd4deb | 2011-02-25 22:07:43 +0000 | [diff] [blame] | 541 | if daemon is not None: |
| 542 | self._daemonic = daemon |
| 543 | else: |
| 544 | self._daemonic = current_thread().daemon |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 545 | self._ident = None |
Christian Heimes | 9e7f1d2 | 2008-02-28 12:27:11 +0000 | [diff] [blame] | 546 | self._started = Event() |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 547 | self._stopped = False |
| 548 | self._block = Condition(Lock()) |
| 549 | self._initialized = True |
Brett Cannon | cc4e935 | 2004-07-03 03:52:35 +0000 | [diff] [blame] | 550 | # sys.stderr is not stored in the class like |
| 551 | # sys.exc_info since it can be changed between instances |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 552 | self._stderr = _sys.stderr |
Antoine Pitrou | c081c0c | 2011-07-15 22:12:24 +0200 | [diff] [blame] | 553 | _dangling.add(self) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 554 | |
Gregory P. Smith | 9bd4a24 | 2011-01-04 18:33:38 +0000 | [diff] [blame] | 555 | def _reset_internal_locks(self): |
| 556 | # private! Called by _after_fork() to reset our internal locks as |
| 557 | # they may be in an invalid state leading to a deadlock or crash. |
| 558 | if hasattr(self, '_block'): # DummyThread deletes _block |
| 559 | self._block.__init__() |
| 560 | self._started._reset_internal_locks() |
| 561 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 562 | def __repr__(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 563 | assert self._initialized, "Thread.__init__() was not called" |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 564 | status = "initial" |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 565 | if self._started.is_set(): |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 566 | status = "started" |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 567 | if self._stopped: |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 568 | status = "stopped" |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 569 | if self._daemonic: |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 570 | status += " daemon" |
| 571 | if self._ident is not None: |
| 572 | status += " %s" % self._ident |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 573 | return "<%s(%s, %s)>" % (self.__class__.__name__, self._name, status) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 574 | |
| 575 | def start(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 576 | if not self._initialized: |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 577 | raise RuntimeError("thread.__init__() not called") |
Christian Heimes | 9e7f1d2 | 2008-02-28 12:27:11 +0000 | [diff] [blame] | 578 | |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 579 | if self._started.is_set(): |
Senthil Kumaran | fdd4d0f | 2010-04-06 03:30:18 +0000 | [diff] [blame] | 580 | raise RuntimeError("threads can only be started once") |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 581 | with _active_limbo_lock: |
| 582 | _limbo[self] = self |
Gregory P. Smith | 3fdd964 | 2010-02-28 18:57:46 +0000 | [diff] [blame] | 583 | try: |
| 584 | _start_new_thread(self._bootstrap, ()) |
| 585 | except Exception: |
| 586 | with _active_limbo_lock: |
| 587 | del _limbo[self] |
| 588 | raise |
Christian Heimes | 9e7f1d2 | 2008-02-28 12:27:11 +0000 | [diff] [blame] | 589 | self._started.wait() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 590 | |
| 591 | def run(self): |
Christian Heimes | d3eb5a15 | 2008-02-24 00:38:49 +0000 | [diff] [blame] | 592 | try: |
| 593 | if self._target: |
| 594 | self._target(*self._args, **self._kwargs) |
| 595 | finally: |
| 596 | # Avoid a refcycle if the thread is running a function with |
| 597 | # an argument that has a member that points to the thread. |
| 598 | del self._target, self._args, self._kwargs |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 599 | |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 600 | def _bootstrap(self): |
Guido van Rossum | 61e21b5 | 2007-08-20 19:06:03 +0000 | [diff] [blame] | 601 | # Wrapper around the real bootstrap code that ignores |
| 602 | # exceptions during interpreter cleanup. Those typically |
| 603 | # happen when a daemon thread wakes up at an unfortunate |
| 604 | # moment, finds the world around it destroyed, and raises some |
| 605 | # random exception *** while trying to report the exception in |
Christian Heimes | 9e7f1d2 | 2008-02-28 12:27:11 +0000 | [diff] [blame] | 606 | # _bootstrap_inner() below ***. Those random exceptions |
Guido van Rossum | 61e21b5 | 2007-08-20 19:06:03 +0000 | [diff] [blame] | 607 | # don't help anybody, and they confuse users, so we suppress |
| 608 | # them. We suppress them only when it appears that the world |
| 609 | # indeed has already been destroyed, so that exceptions in |
Christian Heimes | 9e7f1d2 | 2008-02-28 12:27:11 +0000 | [diff] [blame] | 610 | # _bootstrap_inner() during normal business hours are properly |
Guido van Rossum | 61e21b5 | 2007-08-20 19:06:03 +0000 | [diff] [blame] | 611 | # reported. Also, we only suppress them for daemonic threads; |
| 612 | # if a non-daemonic encounters this, something else is wrong. |
| 613 | try: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 614 | self._bootstrap_inner() |
Guido van Rossum | 61e21b5 | 2007-08-20 19:06:03 +0000 | [diff] [blame] | 615 | except: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 616 | if self._daemonic and _sys is None: |
Guido van Rossum | 61e21b5 | 2007-08-20 19:06:03 +0000 | [diff] [blame] | 617 | return |
| 618 | raise |
| 619 | |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 620 | def _set_ident(self): |
Victor Stinner | 2a12974 | 2011-05-30 23:02:52 +0200 | [diff] [blame] | 621 | self._ident = get_ident() |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 622 | |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 623 | def _bootstrap_inner(self): |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 624 | try: |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 625 | self._set_ident() |
Christian Heimes | 9e7f1d2 | 2008-02-28 12:27:11 +0000 | [diff] [blame] | 626 | self._started.set() |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 627 | with _active_limbo_lock: |
| 628 | _active[self._ident] = self |
| 629 | del _limbo[self] |
Jeremy Hylton | bfccb35 | 2003-06-29 16:58:41 +0000 | [diff] [blame] | 630 | |
| 631 | if _trace_hook: |
Jeremy Hylton | bfccb35 | 2003-06-29 16:58:41 +0000 | [diff] [blame] | 632 | _sys.settrace(_trace_hook) |
| 633 | if _profile_hook: |
Jeremy Hylton | bfccb35 | 2003-06-29 16:58:41 +0000 | [diff] [blame] | 634 | _sys.setprofile(_profile_hook) |
Tim Peters | d1b108b | 2003-06-29 17:24:17 +0000 | [diff] [blame] | 635 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 636 | try: |
| 637 | self.run() |
| 638 | except SystemExit: |
Victor Stinner | 135b6d8 | 2012-03-03 01:32:57 +0100 | [diff] [blame] | 639 | pass |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 640 | except: |
Brett Cannon | cc4e935 | 2004-07-03 03:52:35 +0000 | [diff] [blame] | 641 | # If sys.stderr is no more (most likely from interpreter |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 642 | # shutdown) use self._stderr. Otherwise still use sys (as in |
Brett Cannon | cc4e935 | 2004-07-03 03:52:35 +0000 | [diff] [blame] | 643 | # _sys) in case sys.stderr was redefined since the creation of |
| 644 | # self. |
| 645 | if _sys: |
| 646 | _sys.stderr.write("Exception in thread %s:\n%s\n" % |
Benjamin Peterson | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 647 | (self.name, _format_exc())) |
Brett Cannon | cc4e935 | 2004-07-03 03:52:35 +0000 | [diff] [blame] | 648 | else: |
| 649 | # Do the best job possible w/o a huge amt. of code to |
| 650 | # approximate a traceback (code ideas from |
| 651 | # Lib/traceback.py) |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 652 | exc_type, exc_value, exc_tb = self._exc_info() |
Brett Cannon | cc4e935 | 2004-07-03 03:52:35 +0000 | [diff] [blame] | 653 | try: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 654 | print(( |
Benjamin Peterson | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 655 | "Exception in thread " + self.name + |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 656 | " (most likely raised during interpreter shutdown):"), file=self._stderr) |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 657 | print(( |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 658 | "Traceback (most recent call last):"), file=self._stderr) |
Brett Cannon | cc4e935 | 2004-07-03 03:52:35 +0000 | [diff] [blame] | 659 | while exc_tb: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 660 | print(( |
Brett Cannon | cc4e935 | 2004-07-03 03:52:35 +0000 | [diff] [blame] | 661 | ' File "%s", line %s, in %s' % |
| 662 | (exc_tb.tb_frame.f_code.co_filename, |
| 663 | exc_tb.tb_lineno, |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 664 | exc_tb.tb_frame.f_code.co_name)), file=self._stderr) |
Brett Cannon | cc4e935 | 2004-07-03 03:52:35 +0000 | [diff] [blame] | 665 | exc_tb = exc_tb.tb_next |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 666 | print(("%s: %s" % (exc_type, exc_value)), file=self._stderr) |
Brett Cannon | cc4e935 | 2004-07-03 03:52:35 +0000 | [diff] [blame] | 667 | # Make sure that exc_tb gets deleted since it is a memory |
| 668 | # hog; deleting everything else is just for thoroughness |
| 669 | finally: |
| 670 | del exc_type, exc_value, exc_tb |
Christian Heimes | bbe741d | 2008-03-28 10:53:29 +0000 | [diff] [blame] | 671 | finally: |
| 672 | # Prevent a race in |
| 673 | # test_threading.test_no_refcycle_through_target when |
| 674 | # the exception keeps the target alive past when we |
| 675 | # assert that it's dead. |
| 676 | #XXX self.__exc_clear() |
| 677 | pass |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 678 | finally: |
Christian Heimes | 1af737c | 2008-01-23 08:24:23 +0000 | [diff] [blame] | 679 | with _active_limbo_lock: |
| 680 | self._stop() |
| 681 | try: |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 682 | # We don't call self._delete() because it also |
Christian Heimes | 1af737c | 2008-01-23 08:24:23 +0000 | [diff] [blame] | 683 | # grabs _active_limbo_lock. |
Victor Stinner | 2a12974 | 2011-05-30 23:02:52 +0200 | [diff] [blame] | 684 | del _active[get_ident()] |
Christian Heimes | 1af737c | 2008-01-23 08:24:23 +0000 | [diff] [blame] | 685 | except: |
| 686 | pass |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 687 | |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 688 | def _stop(self): |
Christian Heimes | 969fe57 | 2008-01-25 11:23:10 +0000 | [diff] [blame] | 689 | self._block.acquire() |
| 690 | self._stopped = True |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 691 | self._block.notify_all() |
Christian Heimes | 969fe57 | 2008-01-25 11:23:10 +0000 | [diff] [blame] | 692 | self._block.release() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 693 | |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 694 | def _delete(self): |
Tim Peters | 2142993 | 2004-07-21 03:36:52 +0000 | [diff] [blame] | 695 | "Remove current thread from the dict of currently running threads." |
Brett Cannon | 8b3d92a | 2004-07-21 02:21:58 +0000 | [diff] [blame] | 696 | |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 697 | # Notes about running with _dummy_thread: |
Tim Peters | 2142993 | 2004-07-21 03:36:52 +0000 | [diff] [blame] | 698 | # |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 699 | # Must take care to not raise an exception if _dummy_thread is being |
Tim Peters | 2142993 | 2004-07-21 03:36:52 +0000 | [diff] [blame] | 700 | # used (and thus this module is being used as an instance of |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 701 | # dummy_threading). _dummy_thread.get_ident() always returns -1 since |
| 702 | # there is only one thread if _dummy_thread is being used. Thus |
Tim Peters | 2142993 | 2004-07-21 03:36:52 +0000 | [diff] [blame] | 703 | # len(_active) is always <= 1 here, and any Thread instance created |
| 704 | # overwrites the (if any) thread currently registered in _active. |
| 705 | # |
| 706 | # An instance of _MainThread is always created by 'threading'. This |
| 707 | # gets overwritten the instant an instance of Thread is created; both |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 708 | # threads return -1 from _dummy_thread.get_ident() and thus have the |
Tim Peters | 2142993 | 2004-07-21 03:36:52 +0000 | [diff] [blame] | 709 | # same key in the dict. So when the _MainThread instance created by |
| 710 | # 'threading' tries to clean itself up when atexit calls this method |
| 711 | # it gets a KeyError if another Thread instance was created. |
| 712 | # |
| 713 | # This all means that KeyError from trying to delete something from |
| 714 | # _active if dummy_threading is being used is a red herring. But |
| 715 | # since it isn't if dummy_threading is *not* being used then don't |
| 716 | # hide the exception. |
Brett Cannon | 8b3d92a | 2004-07-21 02:21:58 +0000 | [diff] [blame] | 717 | |
Christian Heimes | 969fe57 | 2008-01-25 11:23:10 +0000 | [diff] [blame] | 718 | try: |
Neal Norwitz | f5c7c2e | 2008-04-05 04:47:45 +0000 | [diff] [blame] | 719 | with _active_limbo_lock: |
Victor Stinner | 2a12974 | 2011-05-30 23:02:52 +0200 | [diff] [blame] | 720 | del _active[get_ident()] |
Neal Norwitz | f5c7c2e | 2008-04-05 04:47:45 +0000 | [diff] [blame] | 721 | # There must not be any python code between the previous line |
| 722 | # and after the lock is released. Otherwise a tracing function |
| 723 | # could try to acquire the lock again in the same thread, (in |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 724 | # current_thread()), and would block. |
Neal Norwitz | f5c7c2e | 2008-04-05 04:47:45 +0000 | [diff] [blame] | 725 | except KeyError: |
| 726 | if 'dummy_threading' not in _sys.modules: |
| 727 | raise |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 728 | |
| 729 | def join(self, timeout=None): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 730 | if not self._initialized: |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 731 | raise RuntimeError("Thread.__init__() not called") |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 732 | if not self._started.is_set(): |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 733 | raise RuntimeError("cannot join thread before it is started") |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 734 | if self is current_thread(): |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 735 | raise RuntimeError("cannot join current thread") |
| 736 | |
Christian Heimes | 969fe57 | 2008-01-25 11:23:10 +0000 | [diff] [blame] | 737 | self._block.acquire() |
| 738 | try: |
Brett Cannon | ad07ff2 | 2005-11-23 02:15:50 +0000 | [diff] [blame] | 739 | if timeout is None: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 740 | while not self._stopped: |
| 741 | self._block.wait() |
Brett Cannon | ad07ff2 | 2005-11-23 02:15:50 +0000 | [diff] [blame] | 742 | else: |
| 743 | deadline = _time() + timeout |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 744 | while not self._stopped: |
Brett Cannon | ad07ff2 | 2005-11-23 02:15:50 +0000 | [diff] [blame] | 745 | delay = deadline - _time() |
| 746 | if delay <= 0: |
Brett Cannon | ad07ff2 | 2005-11-23 02:15:50 +0000 | [diff] [blame] | 747 | break |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 748 | self._block.wait(delay) |
Christian Heimes | 969fe57 | 2008-01-25 11:23:10 +0000 | [diff] [blame] | 749 | finally: |
| 750 | self._block.release() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 751 | |
Benjamin Peterson | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 752 | @property |
| 753 | def name(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 754 | assert self._initialized, "Thread.__init__() not called" |
| 755 | return self._name |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 756 | |
Benjamin Peterson | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 757 | @name.setter |
| 758 | def name(self, name): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 759 | assert self._initialized, "Thread.__init__() not called" |
| 760 | self._name = str(name) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 761 | |
Benjamin Peterson | 773c17b | 2008-08-18 16:45:31 +0000 | [diff] [blame] | 762 | @property |
| 763 | def ident(self): |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 764 | assert self._initialized, "Thread.__init__() not called" |
| 765 | return self._ident |
| 766 | |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 767 | def is_alive(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 768 | assert self._initialized, "Thread.__init__() not called" |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 769 | return self._started.is_set() and not self._stopped |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 770 | |
Benjamin Peterson | b3085c9 | 2008-09-01 23:09:31 +0000 | [diff] [blame] | 771 | isAlive = is_alive |
Benjamin Peterson | f0923f5 | 2008-08-18 22:10:13 +0000 | [diff] [blame] | 772 | |
Benjamin Peterson | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 773 | @property |
| 774 | def daemon(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 775 | assert self._initialized, "Thread.__init__() not called" |
| 776 | return self._daemonic |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 777 | |
Benjamin Peterson | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 778 | @daemon.setter |
| 779 | def daemon(self, daemonic): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 780 | if not self._initialized: |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 781 | raise RuntimeError("Thread.__init__() not called") |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 782 | if self._started.is_set(): |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 783 | raise RuntimeError("cannot set daemon status of active thread"); |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 784 | self._daemonic = daemonic |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 785 | |
Benjamin Peterson | 6640d72 | 2008-08-18 18:16:46 +0000 | [diff] [blame] | 786 | def isDaemon(self): |
| 787 | return self.daemon |
| 788 | |
| 789 | def setDaemon(self, daemonic): |
| 790 | self.daemon = daemonic |
| 791 | |
| 792 | def getName(self): |
| 793 | return self.name |
| 794 | |
| 795 | def setName(self, name): |
| 796 | self.name = name |
| 797 | |
Martin v. Löwis | 44f8696 | 2001-09-05 13:44:54 +0000 | [diff] [blame] | 798 | # The timer class was contributed by Itamar Shtull-Trauring |
| 799 | |
Éric Araujo | 0cdd445 | 2011-07-28 00:28:28 +0200 | [diff] [blame] | 800 | class Timer(Thread): |
Martin v. Löwis | 44f8696 | 2001-09-05 13:44:54 +0000 | [diff] [blame] | 801 | """Call a function after a specified number of seconds: |
Tim Peters | b64bec3 | 2001-09-18 02:26:39 +0000 | [diff] [blame] | 802 | |
R David Murray | 19aeb43 | 2013-03-30 17:19:38 -0400 | [diff] [blame] | 803 | t = Timer(30.0, f, args=None, kwargs=None) |
Martin v. Löwis | 44f8696 | 2001-09-05 13:44:54 +0000 | [diff] [blame] | 804 | t.start() |
| 805 | t.cancel() # stop the timer's action if it's still waiting |
| 806 | """ |
Tim Peters | b64bec3 | 2001-09-18 02:26:39 +0000 | [diff] [blame] | 807 | |
R David Murray | 19aeb43 | 2013-03-30 17:19:38 -0400 | [diff] [blame] | 808 | def __init__(self, interval, function, args=None, kwargs=None): |
Martin v. Löwis | 44f8696 | 2001-09-05 13:44:54 +0000 | [diff] [blame] | 809 | Thread.__init__(self) |
| 810 | self.interval = interval |
| 811 | self.function = function |
R David Murray | 19aeb43 | 2013-03-30 17:19:38 -0400 | [diff] [blame] | 812 | self.args = args if args is not None else [] |
| 813 | self.kwargs = kwargs if kwargs is not None else {} |
Martin v. Löwis | 44f8696 | 2001-09-05 13:44:54 +0000 | [diff] [blame] | 814 | self.finished = Event() |
Tim Peters | b64bec3 | 2001-09-18 02:26:39 +0000 | [diff] [blame] | 815 | |
Martin v. Löwis | 44f8696 | 2001-09-05 13:44:54 +0000 | [diff] [blame] | 816 | def cancel(self): |
| 817 | """Stop the timer if it hasn't finished yet""" |
| 818 | self.finished.set() |
Tim Peters | b64bec3 | 2001-09-18 02:26:39 +0000 | [diff] [blame] | 819 | |
Martin v. Löwis | 44f8696 | 2001-09-05 13:44:54 +0000 | [diff] [blame] | 820 | def run(self): |
| 821 | self.finished.wait(self.interval) |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 822 | if not self.finished.is_set(): |
Martin v. Löwis | 44f8696 | 2001-09-05 13:44:54 +0000 | [diff] [blame] | 823 | self.function(*self.args, **self.kwargs) |
| 824 | self.finished.set() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 825 | |
| 826 | # Special thread class to represent the main thread |
| 827 | # This is garbage collected through an exit handler |
| 828 | |
| 829 | class _MainThread(Thread): |
| 830 | |
| 831 | def __init__(self): |
Antoine Pitrou | 0bd4deb | 2011-02-25 22:07:43 +0000 | [diff] [blame] | 832 | Thread.__init__(self, name="MainThread", daemon=False) |
Christian Heimes | 9e7f1d2 | 2008-02-28 12:27:11 +0000 | [diff] [blame] | 833 | self._started.set() |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 834 | self._set_ident() |
| 835 | with _active_limbo_lock: |
| 836 | _active[self._ident] = self |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 837 | |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 838 | def _exitfunc(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 839 | self._stop() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 840 | t = _pickSomeNonDaemonThread() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 841 | while t: |
| 842 | t.join() |
| 843 | t = _pickSomeNonDaemonThread() |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 844 | self._delete() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 845 | |
| 846 | def _pickSomeNonDaemonThread(): |
| 847 | for t in enumerate(): |
Benjamin Peterson | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 848 | if not t.daemon and t.is_alive(): |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 849 | return t |
| 850 | return None |
| 851 | |
| 852 | |
| 853 | # Dummy thread class to represent threads not started here. |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 854 | # These aren't garbage collected when they die, nor can they be waited for. |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 855 | # If they invoke anything in threading.py that calls current_thread(), they |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 856 | # leave an entry in the _active dict forever after. |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 857 | # Their purpose is to return *something* from current_thread(). |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 858 | # They are marked as daemon threads so we won't wait for them |
| 859 | # when we exit (conform previous semantics). |
| 860 | |
| 861 | class _DummyThread(Thread): |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 862 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 863 | def __init__(self): |
Antoine Pitrou | 0bd4deb | 2011-02-25 22:07:43 +0000 | [diff] [blame] | 864 | Thread.__init__(self, name=_newname("Dummy-%d"), daemon=True) |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 865 | |
Gregory P. Smith | 9bd4a24 | 2011-01-04 18:33:38 +0000 | [diff] [blame] | 866 | # Thread._block consumes an OS-level locking primitive, which |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 867 | # can never be used by a _DummyThread. Since a _DummyThread |
| 868 | # instance is immortal, that's bad, so release this resource. |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 869 | del self._block |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 870 | |
Christian Heimes | 9e7f1d2 | 2008-02-28 12:27:11 +0000 | [diff] [blame] | 871 | self._started.set() |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 872 | self._set_ident() |
| 873 | with _active_limbo_lock: |
| 874 | _active[self._ident] = self |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 875 | |
Antoine Pitrou | 8e6e0fd | 2012-04-19 23:55:01 +0200 | [diff] [blame] | 876 | def _stop(self): |
| 877 | pass |
| 878 | |
Neal Norwitz | 45bec8c | 2002-02-19 03:01:36 +0000 | [diff] [blame] | 879 | def join(self, timeout=None): |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 880 | assert False, "cannot join a dummy thread" |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 881 | |
| 882 | |
| 883 | # Global API functions |
| 884 | |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 885 | def current_thread(): |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 886 | try: |
Victor Stinner | 2a12974 | 2011-05-30 23:02:52 +0200 | [diff] [blame] | 887 | return _active[get_ident()] |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 888 | except KeyError: |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 889 | return _DummyThread() |
| 890 | |
Benjamin Peterson | b3085c9 | 2008-09-01 23:09:31 +0000 | [diff] [blame] | 891 | currentThread = current_thread |
Benjamin Peterson | f0923f5 | 2008-08-18 22:10:13 +0000 | [diff] [blame] | 892 | |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 893 | def active_count(): |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 894 | with _active_limbo_lock: |
| 895 | return len(_active) + len(_limbo) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 896 | |
Benjamin Peterson | b3085c9 | 2008-09-01 23:09:31 +0000 | [diff] [blame] | 897 | activeCount = active_count |
Benjamin Peterson | f0923f5 | 2008-08-18 22:10:13 +0000 | [diff] [blame] | 898 | |
Antoine Pitrou | bdec11f | 2009-11-05 13:49:14 +0000 | [diff] [blame] | 899 | def _enumerate(): |
| 900 | # Same as enumerate(), but without the lock. Internal use only. |
| 901 | return list(_active.values()) + list(_limbo.values()) |
| 902 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 903 | def enumerate(): |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 904 | with _active_limbo_lock: |
| 905 | return list(_active.values()) + list(_limbo.values()) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 906 | |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 907 | from _thread import stack_size |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 908 | |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 909 | # Create the main thread object, |
| 910 | # and make it available for the interpreter |
| 911 | # (Py_Main) as threading._shutdown. |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 912 | |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 913 | _shutdown = _MainThread()._exitfunc |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 914 | |
Jim Fulton | d15dc06 | 2004-07-14 19:11:50 +0000 | [diff] [blame] | 915 | # get thread-local implementation, either from the thread |
| 916 | # module, or from the python fallback |
| 917 | |
| 918 | try: |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 919 | from _thread import _local as local |
Jim Fulton | d15dc06 | 2004-07-14 19:11:50 +0000 | [diff] [blame] | 920 | except ImportError: |
| 921 | from _threading_local import local |
| 922 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 923 | |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 924 | def _after_fork(): |
| 925 | # This function is called by Python/ceval.c:PyEval_ReInitThreads which |
| 926 | # is called from PyOS_AfterFork. Here we cleanup threading module state |
| 927 | # that should not exist after a fork. |
| 928 | |
| 929 | # Reset _active_limbo_lock, in case we forked while the lock was held |
| 930 | # by another (non-forked) thread. http://bugs.python.org/issue874900 |
| 931 | global _active_limbo_lock |
| 932 | _active_limbo_lock = _allocate_lock() |
| 933 | |
| 934 | # fork() only copied the current thread; clear references to others. |
| 935 | new_active = {} |
| 936 | current = current_thread() |
| 937 | with _active_limbo_lock: |
Antoine Pitrou | 5fe291f | 2008-09-06 23:00:03 +0000 | [diff] [blame] | 938 | for thread in _active.values(): |
Charles-François Natali | b055bf6 | 2011-12-18 18:45:16 +0100 | [diff] [blame] | 939 | # Any lock/condition variable may be currently locked or in an |
| 940 | # invalid state, so we reinitialize them. |
| 941 | thread._reset_internal_locks() |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 942 | if thread is current: |
Antoine Pitrou | 5fe291f | 2008-09-06 23:00:03 +0000 | [diff] [blame] | 943 | # There is only one active thread. We reset the ident to |
| 944 | # its new value since it can have changed. |
Victor Stinner | 2a12974 | 2011-05-30 23:02:52 +0200 | [diff] [blame] | 945 | ident = get_ident() |
Antoine Pitrou | 5fe291f | 2008-09-06 23:00:03 +0000 | [diff] [blame] | 946 | thread._ident = ident |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 947 | new_active[ident] = thread |
| 948 | else: |
| 949 | # All the others are already stopped. |
Charles-François Natali | b055bf6 | 2011-12-18 18:45:16 +0100 | [diff] [blame] | 950 | thread._stop() |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 951 | |
| 952 | _limbo.clear() |
| 953 | _active.clear() |
| 954 | _active.update(new_active) |
| 955 | assert len(_active) == 1 |