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 |
Ezio Melotti | 30b9d5d | 2013-08-17 15:50:46 +0300 | [diff] [blame] | 17 | # language. Those original names are not in any imminent danger of |
Benjamin Peterson | b3085c9 | 2008-09-01 23:09:31 +0000 | [diff] [blame] | 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): |
Tim Peters | 7634e1c | 2013-10-08 20:55:51 -0500 | [diff] [blame^] | 286 | with self._cond: |
| 287 | if self._value >= self._initial_value: |
| 288 | raise ValueError("Semaphore released too many times") |
| 289 | self._value += 1 |
| 290 | self._cond.notify() |
Skip Montanaro | e428bb7 | 2001-08-20 20:27:58 +0000 | [diff] [blame] | 291 | |
| 292 | |
Victor Stinner | 135b6d8 | 2012-03-03 01:32:57 +0100 | [diff] [blame] | 293 | class Event: |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 294 | |
| 295 | # After Tim Peters' event class (without is_posted()) |
| 296 | |
Victor Stinner | 135b6d8 | 2012-03-03 01:32:57 +0100 | [diff] [blame] | 297 | def __init__(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 298 | self._cond = Condition(Lock()) |
| 299 | self._flag = False |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 300 | |
Gregory P. Smith | 9bd4a24 | 2011-01-04 18:33:38 +0000 | [diff] [blame] | 301 | def _reset_internal_locks(self): |
| 302 | # private! called by Thread._reset_internal_locks by _after_fork() |
| 303 | self._cond.__init__() |
| 304 | |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 305 | def is_set(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 306 | return self._flag |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 307 | |
Benjamin Peterson | b3085c9 | 2008-09-01 23:09:31 +0000 | [diff] [blame] | 308 | isSet = is_set |
Benjamin Peterson | f0923f5 | 2008-08-18 22:10:13 +0000 | [diff] [blame] | 309 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 310 | def set(self): |
Christian Heimes | 969fe57 | 2008-01-25 11:23:10 +0000 | [diff] [blame] | 311 | self._cond.acquire() |
| 312 | try: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 313 | self._flag = True |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 314 | self._cond.notify_all() |
Christian Heimes | 969fe57 | 2008-01-25 11:23:10 +0000 | [diff] [blame] | 315 | finally: |
| 316 | self._cond.release() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 317 | |
| 318 | def clear(self): |
Christian Heimes | 969fe57 | 2008-01-25 11:23:10 +0000 | [diff] [blame] | 319 | self._cond.acquire() |
| 320 | try: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 321 | self._flag = False |
Christian Heimes | 969fe57 | 2008-01-25 11:23:10 +0000 | [diff] [blame] | 322 | finally: |
| 323 | self._cond.release() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 324 | |
| 325 | def wait(self, timeout=None): |
Christian Heimes | 969fe57 | 2008-01-25 11:23:10 +0000 | [diff] [blame] | 326 | self._cond.acquire() |
| 327 | try: |
Charles-François Natali | ded0348 | 2012-01-07 18:24:56 +0100 | [diff] [blame] | 328 | signaled = self._flag |
| 329 | if not signaled: |
| 330 | signaled = self._cond.wait(timeout) |
| 331 | return signaled |
Christian Heimes | 969fe57 | 2008-01-25 11:23:10 +0000 | [diff] [blame] | 332 | finally: |
| 333 | self._cond.release() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 334 | |
Kristján Valur Jónsson | 3be0003 | 2010-10-28 09:43:10 +0000 | [diff] [blame] | 335 | |
| 336 | # A barrier class. Inspired in part by the pthread_barrier_* api and |
| 337 | # the CyclicBarrier class from Java. See |
| 338 | # http://sourceware.org/pthreads-win32/manual/pthread_barrier_init.html and |
| 339 | # http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/ |
| 340 | # CyclicBarrier.html |
| 341 | # for information. |
| 342 | # We maintain two main states, 'filling' and 'draining' enabling the barrier |
| 343 | # to be cyclic. Threads are not allowed into it until it has fully drained |
| 344 | # since the previous cycle. In addition, a 'resetting' state exists which is |
| 345 | # similar to 'draining' except that threads leave with a BrokenBarrierError, |
Ezio Melotti | e130a52 | 2011-10-19 10:58:56 +0300 | [diff] [blame] | 346 | # and a 'broken' state in which all threads get the exception. |
Victor Stinner | 135b6d8 | 2012-03-03 01:32:57 +0100 | [diff] [blame] | 347 | class Barrier: |
Kristján Valur Jónsson | 3be0003 | 2010-10-28 09:43:10 +0000 | [diff] [blame] | 348 | """ |
| 349 | Barrier. Useful for synchronizing a fixed number of threads |
| 350 | at known synchronization points. Threads block on 'wait()' and are |
| 351 | simultaneously once they have all made that call. |
| 352 | """ |
Victor Stinner | 135b6d8 | 2012-03-03 01:32:57 +0100 | [diff] [blame] | 353 | def __init__(self, parties, action=None, timeout=None): |
Kristján Valur Jónsson | 3be0003 | 2010-10-28 09:43:10 +0000 | [diff] [blame] | 354 | """ |
| 355 | Create a barrier, initialised to 'parties' threads. |
| 356 | 'action' is a callable which, when supplied, will be called |
| 357 | by one of the threads after they have all entered the |
| 358 | barrier and just prior to releasing them all. |
| 359 | If a 'timeout' is provided, it is uses as the default for |
| 360 | all subsequent 'wait()' calls. |
| 361 | """ |
Kristján Valur Jónsson | 3be0003 | 2010-10-28 09:43:10 +0000 | [diff] [blame] | 362 | self._cond = Condition(Lock()) |
| 363 | self._action = action |
| 364 | self._timeout = timeout |
| 365 | self._parties = parties |
| 366 | self._state = 0 #0 filling, 1, draining, -1 resetting, -2 broken |
| 367 | self._count = 0 |
| 368 | |
| 369 | def wait(self, timeout=None): |
| 370 | """ |
| 371 | Wait for the barrier. When the specified number of threads have |
| 372 | started waiting, they are all simultaneously awoken. If an 'action' |
| 373 | was provided for the barrier, one of the threads will have executed |
| 374 | that callback prior to returning. |
| 375 | Returns an individual index number from 0 to 'parties-1'. |
| 376 | """ |
| 377 | if timeout is None: |
| 378 | timeout = self._timeout |
| 379 | with self._cond: |
| 380 | self._enter() # Block while the barrier drains. |
| 381 | index = self._count |
| 382 | self._count += 1 |
| 383 | try: |
| 384 | if index + 1 == self._parties: |
| 385 | # We release the barrier |
| 386 | self._release() |
| 387 | else: |
| 388 | # We wait until someone releases us |
| 389 | self._wait(timeout) |
| 390 | return index |
| 391 | finally: |
| 392 | self._count -= 1 |
| 393 | # Wake up any threads waiting for barrier to drain. |
| 394 | self._exit() |
| 395 | |
| 396 | # Block until the barrier is ready for us, or raise an exception |
| 397 | # if it is broken. |
| 398 | def _enter(self): |
| 399 | while self._state in (-1, 1): |
| 400 | # It is draining or resetting, wait until done |
| 401 | self._cond.wait() |
| 402 | #see if the barrier is in a broken state |
| 403 | if self._state < 0: |
| 404 | raise BrokenBarrierError |
| 405 | assert self._state == 0 |
| 406 | |
| 407 | # Optionally run the 'action' and release the threads waiting |
| 408 | # in the barrier. |
| 409 | def _release(self): |
| 410 | try: |
| 411 | if self._action: |
| 412 | self._action() |
| 413 | # enter draining state |
| 414 | self._state = 1 |
| 415 | self._cond.notify_all() |
| 416 | except: |
| 417 | #an exception during the _action handler. Break and reraise |
| 418 | self._break() |
| 419 | raise |
| 420 | |
| 421 | # Wait in the barrier until we are relased. Raise an exception |
| 422 | # if the barrier is reset or broken. |
| 423 | def _wait(self, timeout): |
Kristján Valur Jónsson | 6331520 | 2010-11-18 12:46:39 +0000 | [diff] [blame] | 424 | if not self._cond.wait_for(lambda : self._state != 0, timeout): |
| 425 | #timed out. Break the barrier |
| 426 | self._break() |
| 427 | raise BrokenBarrierError |
| 428 | if self._state < 0: |
| 429 | raise BrokenBarrierError |
Kristján Valur Jónsson | 3be0003 | 2010-10-28 09:43:10 +0000 | [diff] [blame] | 430 | assert self._state == 1 |
| 431 | |
| 432 | # If we are the last thread to exit the barrier, signal any threads |
| 433 | # waiting for the barrier to drain. |
| 434 | def _exit(self): |
| 435 | if self._count == 0: |
| 436 | if self._state in (-1, 1): |
| 437 | #resetting or draining |
| 438 | self._state = 0 |
| 439 | self._cond.notify_all() |
| 440 | |
| 441 | def reset(self): |
| 442 | """ |
| 443 | Reset the barrier to the initial state. |
| 444 | Any threads currently waiting will get the BrokenBarrier exception |
| 445 | raised. |
| 446 | """ |
| 447 | with self._cond: |
| 448 | if self._count > 0: |
| 449 | if self._state == 0: |
| 450 | #reset the barrier, waking up threads |
| 451 | self._state = -1 |
| 452 | elif self._state == -2: |
| 453 | #was broken, set it to reset state |
| 454 | #which clears when the last thread exits |
| 455 | self._state = -1 |
| 456 | else: |
| 457 | self._state = 0 |
| 458 | self._cond.notify_all() |
| 459 | |
| 460 | def abort(self): |
| 461 | """ |
| 462 | Place the barrier into a 'broken' state. |
| 463 | Useful in case of error. Any currently waiting threads and |
| 464 | threads attempting to 'wait()' will have BrokenBarrierError |
| 465 | raised. |
| 466 | """ |
| 467 | with self._cond: |
| 468 | self._break() |
| 469 | |
| 470 | def _break(self): |
| 471 | # An internal error was detected. The barrier is set to |
| 472 | # a broken state all parties awakened. |
| 473 | self._state = -2 |
| 474 | self._cond.notify_all() |
| 475 | |
| 476 | @property |
| 477 | def parties(self): |
| 478 | """ |
| 479 | Return the number of threads required to trip the barrier. |
| 480 | """ |
| 481 | return self._parties |
| 482 | |
| 483 | @property |
| 484 | def n_waiting(self): |
| 485 | """ |
| 486 | Return the number of threads that are currently waiting at the barrier. |
| 487 | """ |
| 488 | # We don't need synchronization here since this is an ephemeral result |
| 489 | # anyway. It returns the correct value in the steady state. |
| 490 | if self._state == 0: |
| 491 | return self._count |
| 492 | return 0 |
| 493 | |
| 494 | @property |
| 495 | def broken(self): |
| 496 | """ |
| 497 | Return True if the barrier is in a broken state |
| 498 | """ |
| 499 | return self._state == -2 |
| 500 | |
| 501 | #exception raised by the Barrier class |
| 502 | class BrokenBarrierError(RuntimeError): pass |
| 503 | |
| 504 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 505 | # Helper to generate new thread names |
| 506 | _counter = 0 |
| 507 | def _newname(template="Thread-%d"): |
| 508 | global _counter |
| 509 | _counter = _counter + 1 |
| 510 | return template % _counter |
| 511 | |
| 512 | # Active thread administration |
| 513 | _active_limbo_lock = _allocate_lock() |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 514 | _active = {} # maps thread id to Thread object |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 515 | _limbo = {} |
| 516 | |
Antoine Pitrou | c081c0c | 2011-07-15 22:12:24 +0200 | [diff] [blame] | 517 | # For debug and leak testing |
| 518 | _dangling = WeakSet() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 519 | |
| 520 | # Main class for threads |
| 521 | |
Victor Stinner | 135b6d8 | 2012-03-03 01:32:57 +0100 | [diff] [blame] | 522 | class Thread: |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 523 | |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 524 | __initialized = False |
Brett Cannon | cc4e935 | 2004-07-03 03:52:35 +0000 | [diff] [blame] | 525 | # Need to store a reference to sys.exc_info for printing |
| 526 | # out exceptions when a thread tries to use a global var. during interp. |
| 527 | # shutdown and thus raises an exception about trying to perform some |
| 528 | # operation on/with a NoneType |
| 529 | __exc_info = _sys.exc_info |
Christian Heimes | bbe741d | 2008-03-28 10:53:29 +0000 | [diff] [blame] | 530 | # Keep sys.exc_clear too to clear the exception just before |
| 531 | # allowing .join() to return. |
| 532 | #XXX __exc_clear = _sys.exc_clear |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 533 | |
| 534 | def __init__(self, group=None, target=None, name=None, |
Victor Stinner | 135b6d8 | 2012-03-03 01:32:57 +0100 | [diff] [blame] | 535 | args=(), kwargs=None, *, daemon=None): |
Guido van Rossum | 5a43e1a | 1998-06-09 19:04:26 +0000 | [diff] [blame] | 536 | assert group is None, "group argument must be None for now" |
Georg Brandl | a4a8b82 | 2005-07-15 09:13:21 +0000 | [diff] [blame] | 537 | if kwargs is None: |
| 538 | kwargs = {} |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 539 | self._target = target |
| 540 | self._name = str(name or _newname()) |
| 541 | self._args = args |
| 542 | self._kwargs = kwargs |
Antoine Pitrou | 0bd4deb | 2011-02-25 22:07:43 +0000 | [diff] [blame] | 543 | if daemon is not None: |
| 544 | self._daemonic = daemon |
| 545 | else: |
| 546 | self._daemonic = current_thread().daemon |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 547 | self._ident = None |
Christian Heimes | 9e7f1d2 | 2008-02-28 12:27:11 +0000 | [diff] [blame] | 548 | self._started = Event() |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 549 | self._stopped = False |
| 550 | self._block = Condition(Lock()) |
| 551 | self._initialized = True |
Brett Cannon | cc4e935 | 2004-07-03 03:52:35 +0000 | [diff] [blame] | 552 | # sys.stderr is not stored in the class like |
| 553 | # sys.exc_info since it can be changed between instances |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 554 | self._stderr = _sys.stderr |
Antoine Pitrou | c081c0c | 2011-07-15 22:12:24 +0200 | [diff] [blame] | 555 | _dangling.add(self) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 556 | |
Gregory P. Smith | 9bd4a24 | 2011-01-04 18:33:38 +0000 | [diff] [blame] | 557 | def _reset_internal_locks(self): |
| 558 | # private! Called by _after_fork() to reset our internal locks as |
| 559 | # they may be in an invalid state leading to a deadlock or crash. |
| 560 | if hasattr(self, '_block'): # DummyThread deletes _block |
| 561 | self._block.__init__() |
| 562 | self._started._reset_internal_locks() |
| 563 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 564 | def __repr__(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 565 | assert self._initialized, "Thread.__init__() was not called" |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 566 | status = "initial" |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 567 | if self._started.is_set(): |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 568 | status = "started" |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 569 | if self._stopped: |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 570 | status = "stopped" |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 571 | if self._daemonic: |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 572 | status += " daemon" |
| 573 | if self._ident is not None: |
| 574 | status += " %s" % self._ident |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 575 | return "<%s(%s, %s)>" % (self.__class__.__name__, self._name, status) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 576 | |
| 577 | def start(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 578 | if not self._initialized: |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 579 | raise RuntimeError("thread.__init__() not called") |
Christian Heimes | 9e7f1d2 | 2008-02-28 12:27:11 +0000 | [diff] [blame] | 580 | |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 581 | if self._started.is_set(): |
Senthil Kumaran | fdd4d0f | 2010-04-06 03:30:18 +0000 | [diff] [blame] | 582 | raise RuntimeError("threads can only be started once") |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 583 | with _active_limbo_lock: |
| 584 | _limbo[self] = self |
Gregory P. Smith | 3fdd964 | 2010-02-28 18:57:46 +0000 | [diff] [blame] | 585 | try: |
| 586 | _start_new_thread(self._bootstrap, ()) |
| 587 | except Exception: |
| 588 | with _active_limbo_lock: |
| 589 | del _limbo[self] |
| 590 | raise |
Christian Heimes | 9e7f1d2 | 2008-02-28 12:27:11 +0000 | [diff] [blame] | 591 | self._started.wait() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 592 | |
| 593 | def run(self): |
Christian Heimes | d3eb5a15 | 2008-02-24 00:38:49 +0000 | [diff] [blame] | 594 | try: |
| 595 | if self._target: |
| 596 | self._target(*self._args, **self._kwargs) |
| 597 | finally: |
| 598 | # Avoid a refcycle if the thread is running a function with |
| 599 | # an argument that has a member that points to the thread. |
| 600 | del self._target, self._args, self._kwargs |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 601 | |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 602 | def _bootstrap(self): |
Guido van Rossum | 61e21b5 | 2007-08-20 19:06:03 +0000 | [diff] [blame] | 603 | # Wrapper around the real bootstrap code that ignores |
| 604 | # exceptions during interpreter cleanup. Those typically |
| 605 | # happen when a daemon thread wakes up at an unfortunate |
| 606 | # moment, finds the world around it destroyed, and raises some |
| 607 | # random exception *** while trying to report the exception in |
Christian Heimes | 9e7f1d2 | 2008-02-28 12:27:11 +0000 | [diff] [blame] | 608 | # _bootstrap_inner() below ***. Those random exceptions |
Guido van Rossum | 61e21b5 | 2007-08-20 19:06:03 +0000 | [diff] [blame] | 609 | # don't help anybody, and they confuse users, so we suppress |
| 610 | # them. We suppress them only when it appears that the world |
| 611 | # indeed has already been destroyed, so that exceptions in |
Christian Heimes | 9e7f1d2 | 2008-02-28 12:27:11 +0000 | [diff] [blame] | 612 | # _bootstrap_inner() during normal business hours are properly |
Guido van Rossum | 61e21b5 | 2007-08-20 19:06:03 +0000 | [diff] [blame] | 613 | # reported. Also, we only suppress them for daemonic threads; |
| 614 | # if a non-daemonic encounters this, something else is wrong. |
| 615 | try: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 616 | self._bootstrap_inner() |
Guido van Rossum | 61e21b5 | 2007-08-20 19:06:03 +0000 | [diff] [blame] | 617 | except: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 618 | if self._daemonic and _sys is None: |
Guido van Rossum | 61e21b5 | 2007-08-20 19:06:03 +0000 | [diff] [blame] | 619 | return |
| 620 | raise |
| 621 | |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 622 | def _set_ident(self): |
Victor Stinner | 2a12974 | 2011-05-30 23:02:52 +0200 | [diff] [blame] | 623 | self._ident = get_ident() |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 624 | |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 625 | def _bootstrap_inner(self): |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 626 | try: |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 627 | self._set_ident() |
Christian Heimes | 9e7f1d2 | 2008-02-28 12:27:11 +0000 | [diff] [blame] | 628 | self._started.set() |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 629 | with _active_limbo_lock: |
| 630 | _active[self._ident] = self |
| 631 | del _limbo[self] |
Jeremy Hylton | bfccb35 | 2003-06-29 16:58:41 +0000 | [diff] [blame] | 632 | |
| 633 | if _trace_hook: |
Jeremy Hylton | bfccb35 | 2003-06-29 16:58:41 +0000 | [diff] [blame] | 634 | _sys.settrace(_trace_hook) |
| 635 | if _profile_hook: |
Jeremy Hylton | bfccb35 | 2003-06-29 16:58:41 +0000 | [diff] [blame] | 636 | _sys.setprofile(_profile_hook) |
Tim Peters | d1b108b | 2003-06-29 17:24:17 +0000 | [diff] [blame] | 637 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 638 | try: |
| 639 | self.run() |
| 640 | except SystemExit: |
Victor Stinner | 135b6d8 | 2012-03-03 01:32:57 +0100 | [diff] [blame] | 641 | pass |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 642 | except: |
Brett Cannon | cc4e935 | 2004-07-03 03:52:35 +0000 | [diff] [blame] | 643 | # If sys.stderr is no more (most likely from interpreter |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 644 | # shutdown) use self._stderr. Otherwise still use sys (as in |
Brett Cannon | cc4e935 | 2004-07-03 03:52:35 +0000 | [diff] [blame] | 645 | # _sys) in case sys.stderr was redefined since the creation of |
| 646 | # self. |
| 647 | if _sys: |
| 648 | _sys.stderr.write("Exception in thread %s:\n%s\n" % |
Benjamin Peterson | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 649 | (self.name, _format_exc())) |
Brett Cannon | cc4e935 | 2004-07-03 03:52:35 +0000 | [diff] [blame] | 650 | else: |
| 651 | # Do the best job possible w/o a huge amt. of code to |
| 652 | # approximate a traceback (code ideas from |
| 653 | # Lib/traceback.py) |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 654 | exc_type, exc_value, exc_tb = self._exc_info() |
Brett Cannon | cc4e935 | 2004-07-03 03:52:35 +0000 | [diff] [blame] | 655 | try: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 656 | print(( |
Benjamin Peterson | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 657 | "Exception in thread " + self.name + |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 658 | " (most likely raised during interpreter shutdown):"), file=self._stderr) |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 659 | print(( |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 660 | "Traceback (most recent call last):"), file=self._stderr) |
Brett Cannon | cc4e935 | 2004-07-03 03:52:35 +0000 | [diff] [blame] | 661 | while exc_tb: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 662 | print(( |
Brett Cannon | cc4e935 | 2004-07-03 03:52:35 +0000 | [diff] [blame] | 663 | ' File "%s", line %s, in %s' % |
| 664 | (exc_tb.tb_frame.f_code.co_filename, |
| 665 | exc_tb.tb_lineno, |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 666 | exc_tb.tb_frame.f_code.co_name)), file=self._stderr) |
Brett Cannon | cc4e935 | 2004-07-03 03:52:35 +0000 | [diff] [blame] | 667 | exc_tb = exc_tb.tb_next |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 668 | print(("%s: %s" % (exc_type, exc_value)), file=self._stderr) |
Brett Cannon | cc4e935 | 2004-07-03 03:52:35 +0000 | [diff] [blame] | 669 | # Make sure that exc_tb gets deleted since it is a memory |
| 670 | # hog; deleting everything else is just for thoroughness |
| 671 | finally: |
| 672 | del exc_type, exc_value, exc_tb |
Christian Heimes | bbe741d | 2008-03-28 10:53:29 +0000 | [diff] [blame] | 673 | finally: |
| 674 | # Prevent a race in |
| 675 | # test_threading.test_no_refcycle_through_target when |
| 676 | # the exception keeps the target alive past when we |
| 677 | # assert that it's dead. |
| 678 | #XXX self.__exc_clear() |
| 679 | pass |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 680 | finally: |
Christian Heimes | 1af737c | 2008-01-23 08:24:23 +0000 | [diff] [blame] | 681 | with _active_limbo_lock: |
| 682 | self._stop() |
| 683 | try: |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 684 | # We don't call self._delete() because it also |
Christian Heimes | 1af737c | 2008-01-23 08:24:23 +0000 | [diff] [blame] | 685 | # grabs _active_limbo_lock. |
Victor Stinner | 2a12974 | 2011-05-30 23:02:52 +0200 | [diff] [blame] | 686 | del _active[get_ident()] |
Christian Heimes | 1af737c | 2008-01-23 08:24:23 +0000 | [diff] [blame] | 687 | except: |
| 688 | pass |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 689 | |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 690 | def _stop(self): |
Christian Heimes | 969fe57 | 2008-01-25 11:23:10 +0000 | [diff] [blame] | 691 | self._block.acquire() |
| 692 | self._stopped = True |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 693 | self._block.notify_all() |
Christian Heimes | 969fe57 | 2008-01-25 11:23:10 +0000 | [diff] [blame] | 694 | self._block.release() |
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 _delete(self): |
Tim Peters | 2142993 | 2004-07-21 03:36:52 +0000 | [diff] [blame] | 697 | "Remove current thread from the dict of currently running threads." |
Brett Cannon | 8b3d92a | 2004-07-21 02:21:58 +0000 | [diff] [blame] | 698 | |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 699 | # Notes about running with _dummy_thread: |
Tim Peters | 2142993 | 2004-07-21 03:36:52 +0000 | [diff] [blame] | 700 | # |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 701 | # 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] | 702 | # used (and thus this module is being used as an instance of |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 703 | # dummy_threading). _dummy_thread.get_ident() always returns -1 since |
| 704 | # there is only one thread if _dummy_thread is being used. Thus |
Tim Peters | 2142993 | 2004-07-21 03:36:52 +0000 | [diff] [blame] | 705 | # len(_active) is always <= 1 here, and any Thread instance created |
| 706 | # overwrites the (if any) thread currently registered in _active. |
| 707 | # |
| 708 | # An instance of _MainThread is always created by 'threading'. This |
| 709 | # gets overwritten the instant an instance of Thread is created; both |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 710 | # threads return -1 from _dummy_thread.get_ident() and thus have the |
Tim Peters | 2142993 | 2004-07-21 03:36:52 +0000 | [diff] [blame] | 711 | # same key in the dict. So when the _MainThread instance created by |
| 712 | # 'threading' tries to clean itself up when atexit calls this method |
| 713 | # it gets a KeyError if another Thread instance was created. |
| 714 | # |
| 715 | # This all means that KeyError from trying to delete something from |
| 716 | # _active if dummy_threading is being used is a red herring. But |
| 717 | # since it isn't if dummy_threading is *not* being used then don't |
| 718 | # hide the exception. |
Brett Cannon | 8b3d92a | 2004-07-21 02:21:58 +0000 | [diff] [blame] | 719 | |
Christian Heimes | 969fe57 | 2008-01-25 11:23:10 +0000 | [diff] [blame] | 720 | try: |
Neal Norwitz | f5c7c2e | 2008-04-05 04:47:45 +0000 | [diff] [blame] | 721 | with _active_limbo_lock: |
Victor Stinner | 2a12974 | 2011-05-30 23:02:52 +0200 | [diff] [blame] | 722 | del _active[get_ident()] |
Neal Norwitz | f5c7c2e | 2008-04-05 04:47:45 +0000 | [diff] [blame] | 723 | # There must not be any python code between the previous line |
| 724 | # and after the lock is released. Otherwise a tracing function |
| 725 | # could try to acquire the lock again in the same thread, (in |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 726 | # current_thread()), and would block. |
Neal Norwitz | f5c7c2e | 2008-04-05 04:47:45 +0000 | [diff] [blame] | 727 | except KeyError: |
| 728 | if 'dummy_threading' not in _sys.modules: |
| 729 | raise |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 730 | |
| 731 | def join(self, timeout=None): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 732 | if not self._initialized: |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 733 | raise RuntimeError("Thread.__init__() not called") |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 734 | if not self._started.is_set(): |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 735 | raise RuntimeError("cannot join thread before it is started") |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 736 | if self is current_thread(): |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 737 | raise RuntimeError("cannot join current thread") |
| 738 | |
Christian Heimes | 969fe57 | 2008-01-25 11:23:10 +0000 | [diff] [blame] | 739 | self._block.acquire() |
| 740 | try: |
Brett Cannon | ad07ff2 | 2005-11-23 02:15:50 +0000 | [diff] [blame] | 741 | if timeout is None: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 742 | while not self._stopped: |
| 743 | self._block.wait() |
Brett Cannon | ad07ff2 | 2005-11-23 02:15:50 +0000 | [diff] [blame] | 744 | else: |
| 745 | deadline = _time() + timeout |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 746 | while not self._stopped: |
Brett Cannon | ad07ff2 | 2005-11-23 02:15:50 +0000 | [diff] [blame] | 747 | delay = deadline - _time() |
| 748 | if delay <= 0: |
Brett Cannon | ad07ff2 | 2005-11-23 02:15:50 +0000 | [diff] [blame] | 749 | break |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 750 | self._block.wait(delay) |
Christian Heimes | 969fe57 | 2008-01-25 11:23:10 +0000 | [diff] [blame] | 751 | finally: |
| 752 | self._block.release() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 753 | |
Benjamin Peterson | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 754 | @property |
| 755 | def name(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 756 | assert self._initialized, "Thread.__init__() not called" |
| 757 | return self._name |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 758 | |
Benjamin Peterson | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 759 | @name.setter |
| 760 | def name(self, name): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 761 | assert self._initialized, "Thread.__init__() not called" |
| 762 | self._name = str(name) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 763 | |
Benjamin Peterson | 773c17b | 2008-08-18 16:45:31 +0000 | [diff] [blame] | 764 | @property |
| 765 | def ident(self): |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 766 | assert self._initialized, "Thread.__init__() not called" |
| 767 | return self._ident |
| 768 | |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 769 | def is_alive(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 770 | assert self._initialized, "Thread.__init__() not called" |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 771 | return self._started.is_set() and not self._stopped |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 772 | |
Benjamin Peterson | b3085c9 | 2008-09-01 23:09:31 +0000 | [diff] [blame] | 773 | isAlive = is_alive |
Benjamin Peterson | f0923f5 | 2008-08-18 22:10:13 +0000 | [diff] [blame] | 774 | |
Benjamin Peterson | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 775 | @property |
| 776 | def daemon(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 777 | assert self._initialized, "Thread.__init__() not called" |
| 778 | return self._daemonic |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 779 | |
Benjamin Peterson | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 780 | @daemon.setter |
| 781 | def daemon(self, daemonic): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 782 | if not self._initialized: |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 783 | raise RuntimeError("Thread.__init__() not called") |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 784 | if self._started.is_set(): |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 785 | raise RuntimeError("cannot set daemon status of active thread"); |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 786 | self._daemonic = daemonic |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 787 | |
Benjamin Peterson | 6640d72 | 2008-08-18 18:16:46 +0000 | [diff] [blame] | 788 | def isDaemon(self): |
| 789 | return self.daemon |
| 790 | |
| 791 | def setDaemon(self, daemonic): |
| 792 | self.daemon = daemonic |
| 793 | |
| 794 | def getName(self): |
| 795 | return self.name |
| 796 | |
| 797 | def setName(self, name): |
| 798 | self.name = name |
| 799 | |
Martin v. Löwis | 44f8696 | 2001-09-05 13:44:54 +0000 | [diff] [blame] | 800 | # The timer class was contributed by Itamar Shtull-Trauring |
| 801 | |
Éric Araujo | 0cdd445 | 2011-07-28 00:28:28 +0200 | [diff] [blame] | 802 | class Timer(Thread): |
Martin v. Löwis | 44f8696 | 2001-09-05 13:44:54 +0000 | [diff] [blame] | 803 | """Call a function after a specified number of seconds: |
Tim Peters | b64bec3 | 2001-09-18 02:26:39 +0000 | [diff] [blame] | 804 | |
R David Murray | 19aeb43 | 2013-03-30 17:19:38 -0400 | [diff] [blame] | 805 | t = Timer(30.0, f, args=None, kwargs=None) |
Martin v. Löwis | 44f8696 | 2001-09-05 13:44:54 +0000 | [diff] [blame] | 806 | t.start() |
| 807 | t.cancel() # stop the timer's action if it's still waiting |
| 808 | """ |
Tim Peters | b64bec3 | 2001-09-18 02:26:39 +0000 | [diff] [blame] | 809 | |
R David Murray | 19aeb43 | 2013-03-30 17:19:38 -0400 | [diff] [blame] | 810 | def __init__(self, interval, function, args=None, kwargs=None): |
Martin v. Löwis | 44f8696 | 2001-09-05 13:44:54 +0000 | [diff] [blame] | 811 | Thread.__init__(self) |
| 812 | self.interval = interval |
| 813 | self.function = function |
R David Murray | 19aeb43 | 2013-03-30 17:19:38 -0400 | [diff] [blame] | 814 | self.args = args if args is not None else [] |
| 815 | self.kwargs = kwargs if kwargs is not None else {} |
Martin v. Löwis | 44f8696 | 2001-09-05 13:44:54 +0000 | [diff] [blame] | 816 | self.finished = Event() |
Tim Peters | b64bec3 | 2001-09-18 02:26:39 +0000 | [diff] [blame] | 817 | |
Martin v. Löwis | 44f8696 | 2001-09-05 13:44:54 +0000 | [diff] [blame] | 818 | def cancel(self): |
| 819 | """Stop the timer if it hasn't finished yet""" |
| 820 | self.finished.set() |
Tim Peters | b64bec3 | 2001-09-18 02:26:39 +0000 | [diff] [blame] | 821 | |
Martin v. Löwis | 44f8696 | 2001-09-05 13:44:54 +0000 | [diff] [blame] | 822 | def run(self): |
| 823 | self.finished.wait(self.interval) |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 824 | if not self.finished.is_set(): |
Martin v. Löwis | 44f8696 | 2001-09-05 13:44:54 +0000 | [diff] [blame] | 825 | self.function(*self.args, **self.kwargs) |
| 826 | self.finished.set() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 827 | |
| 828 | # Special thread class to represent the main thread |
| 829 | # This is garbage collected through an exit handler |
| 830 | |
| 831 | class _MainThread(Thread): |
| 832 | |
| 833 | def __init__(self): |
Antoine Pitrou | 0bd4deb | 2011-02-25 22:07:43 +0000 | [diff] [blame] | 834 | Thread.__init__(self, name="MainThread", daemon=False) |
Christian Heimes | 9e7f1d2 | 2008-02-28 12:27:11 +0000 | [diff] [blame] | 835 | self._started.set() |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 836 | self._set_ident() |
| 837 | with _active_limbo_lock: |
| 838 | _active[self._ident] = self |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 839 | |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 840 | def _exitfunc(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 841 | self._stop() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 842 | t = _pickSomeNonDaemonThread() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 843 | while t: |
| 844 | t.join() |
| 845 | t = _pickSomeNonDaemonThread() |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 846 | self._delete() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 847 | |
| 848 | def _pickSomeNonDaemonThread(): |
| 849 | for t in enumerate(): |
Benjamin Peterson | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 850 | if not t.daemon and t.is_alive(): |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 851 | return t |
| 852 | return None |
| 853 | |
| 854 | |
| 855 | # Dummy thread class to represent threads not started here. |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 856 | # 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] | 857 | # If they invoke anything in threading.py that calls current_thread(), they |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 858 | # leave an entry in the _active dict forever after. |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 859 | # Their purpose is to return *something* from current_thread(). |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 860 | # They are marked as daemon threads so we won't wait for them |
| 861 | # when we exit (conform previous semantics). |
| 862 | |
| 863 | class _DummyThread(Thread): |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 864 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 865 | def __init__(self): |
Antoine Pitrou | 0bd4deb | 2011-02-25 22:07:43 +0000 | [diff] [blame] | 866 | Thread.__init__(self, name=_newname("Dummy-%d"), daemon=True) |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 867 | |
Gregory P. Smith | 9bd4a24 | 2011-01-04 18:33:38 +0000 | [diff] [blame] | 868 | # Thread._block consumes an OS-level locking primitive, which |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 869 | # can never be used by a _DummyThread. Since a _DummyThread |
| 870 | # instance is immortal, that's bad, so release this resource. |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 871 | del self._block |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 872 | |
Christian Heimes | 9e7f1d2 | 2008-02-28 12:27:11 +0000 | [diff] [blame] | 873 | self._started.set() |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 874 | self._set_ident() |
| 875 | with _active_limbo_lock: |
| 876 | _active[self._ident] = self |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 877 | |
Antoine Pitrou | 8e6e0fd | 2012-04-19 23:55:01 +0200 | [diff] [blame] | 878 | def _stop(self): |
| 879 | pass |
| 880 | |
Neal Norwitz | 45bec8c | 2002-02-19 03:01:36 +0000 | [diff] [blame] | 881 | def join(self, timeout=None): |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 882 | assert False, "cannot join a dummy thread" |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 883 | |
| 884 | |
| 885 | # Global API functions |
| 886 | |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 887 | def current_thread(): |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 888 | try: |
Victor Stinner | 2a12974 | 2011-05-30 23:02:52 +0200 | [diff] [blame] | 889 | return _active[get_ident()] |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 890 | except KeyError: |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 891 | return _DummyThread() |
| 892 | |
Benjamin Peterson | b3085c9 | 2008-09-01 23:09:31 +0000 | [diff] [blame] | 893 | currentThread = current_thread |
Benjamin Peterson | f0923f5 | 2008-08-18 22:10:13 +0000 | [diff] [blame] | 894 | |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 895 | def active_count(): |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 896 | with _active_limbo_lock: |
| 897 | return len(_active) + len(_limbo) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 898 | |
Benjamin Peterson | b3085c9 | 2008-09-01 23:09:31 +0000 | [diff] [blame] | 899 | activeCount = active_count |
Benjamin Peterson | f0923f5 | 2008-08-18 22:10:13 +0000 | [diff] [blame] | 900 | |
Antoine Pitrou | bdec11f | 2009-11-05 13:49:14 +0000 | [diff] [blame] | 901 | def _enumerate(): |
| 902 | # Same as enumerate(), but without the lock. Internal use only. |
| 903 | return list(_active.values()) + list(_limbo.values()) |
| 904 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 905 | def enumerate(): |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 906 | with _active_limbo_lock: |
| 907 | return list(_active.values()) + list(_limbo.values()) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 908 | |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 909 | from _thread import stack_size |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 910 | |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 911 | # Create the main thread object, |
| 912 | # and make it available for the interpreter |
| 913 | # (Py_Main) as threading._shutdown. |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 914 | |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 915 | _shutdown = _MainThread()._exitfunc |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 916 | |
Jim Fulton | d15dc06 | 2004-07-14 19:11:50 +0000 | [diff] [blame] | 917 | # get thread-local implementation, either from the thread |
| 918 | # module, or from the python fallback |
| 919 | |
| 920 | try: |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 921 | from _thread import _local as local |
Jim Fulton | d15dc06 | 2004-07-14 19:11:50 +0000 | [diff] [blame] | 922 | except ImportError: |
| 923 | from _threading_local import local |
| 924 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 925 | |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 926 | def _after_fork(): |
| 927 | # This function is called by Python/ceval.c:PyEval_ReInitThreads which |
| 928 | # is called from PyOS_AfterFork. Here we cleanup threading module state |
| 929 | # that should not exist after a fork. |
| 930 | |
| 931 | # Reset _active_limbo_lock, in case we forked while the lock was held |
| 932 | # by another (non-forked) thread. http://bugs.python.org/issue874900 |
| 933 | global _active_limbo_lock |
| 934 | _active_limbo_lock = _allocate_lock() |
| 935 | |
| 936 | # fork() only copied the current thread; clear references to others. |
| 937 | new_active = {} |
| 938 | current = current_thread() |
| 939 | with _active_limbo_lock: |
Charles-François Natali | 9939cc8 | 2013-08-30 23:32:53 +0200 | [diff] [blame] | 940 | for thread in _enumerate(): |
Charles-François Natali | b055bf6 | 2011-12-18 18:45:16 +0100 | [diff] [blame] | 941 | # Any lock/condition variable may be currently locked or in an |
| 942 | # invalid state, so we reinitialize them. |
| 943 | thread._reset_internal_locks() |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 944 | if thread is current: |
Antoine Pitrou | 5fe291f | 2008-09-06 23:00:03 +0000 | [diff] [blame] | 945 | # There is only one active thread. We reset the ident to |
| 946 | # its new value since it can have changed. |
Victor Stinner | 2a12974 | 2011-05-30 23:02:52 +0200 | [diff] [blame] | 947 | ident = get_ident() |
Antoine Pitrou | 5fe291f | 2008-09-06 23:00:03 +0000 | [diff] [blame] | 948 | thread._ident = ident |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 949 | new_active[ident] = thread |
| 950 | else: |
| 951 | # All the others are already stopped. |
Charles-François Natali | b055bf6 | 2011-12-18 18:45:16 +0100 | [diff] [blame] | 952 | thread._stop() |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 953 | |
| 954 | _limbo.clear() |
| 955 | _active.clear() |
| 956 | _active.update(new_active) |
| 957 | assert len(_active) == 1 |