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