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