blob: c7c4478178d90925748ebe87775bf241dc0741ee [file] [log] [blame]
Jeremy Hylton92bb6e72002-08-14 19:25:42 +00001"""Thread module emulating a subset of Java's threading model."""
Guido van Rossum7f5013a1998-04-09 22:01:42 +00002
Fred Drakea8725952002-12-30 23:32:50 +00003import sys as _sys
Georg Brandl2067bfd2008-05-25 13:05:15 +00004import _thread
Fred Drakea8725952002-12-30 23:32:50 +00005
Victor Stinnerec895392012-04-29 02:41:27 +02006try:
7 from time import monotonic as _time
Brett Cannoncd171c82013-07-04 17:43:24 -04008except ImportError:
Victor Stinnerec895392012-04-29 02:41:27 +02009 from time import time as _time
Neil Schemenauerf607fc52003-11-05 23:03:00 +000010from traceback import format_exc as _format_exc
Antoine Pitrouc081c0c2011-07-15 22:12:24 +020011from _weakrefset import WeakSet
Raymond Hettinger30307282013-03-20 19:28:19 -070012from itertools import islice as _islice
Raymond Hettingerec4b1742013-03-10 17:57:28 -070013try:
Raymond Hettingerec4b1742013-03-10 17:57:28 -070014 from _collections import deque as _deque
Brett Cannoncd171c82013-07-04 17:43:24 -040015except ImportError:
Raymond Hettingerec4b1742013-03-10 17:57:28 -070016 from collections import deque as _deque
Guido van Rossum7f5013a1998-04-09 22:01:42 +000017
Benjamin Petersonb3085c92008-09-01 23:09:31 +000018# Note regarding PEP 8 compliant names
19# This threading model was originally inspired by Java, and inherited
20# the convention of camelCase function and method names from that
Ezio Melotti30b9d5d2013-08-17 15:50:46 +030021# language. Those original names are not in any imminent danger of
Benjamin Petersonb3085c92008-09-01 23:09:31 +000022# being deprecated (even for Py3k),so this module provides them as an
23# alias for the PEP 8 compliant names
24# Note that using the new PEP 8 compliant names facilitates substitution
25# with the multiprocessing module, which doesn't provide the old
26# Java inspired names.
27
Benjamin Peterson672b8032008-06-11 19:14:14 +000028__all__ = ['active_count', 'Condition', 'current_thread', 'enumerate', 'Event',
Raymond Hettinger5cee47f2011-01-11 19:59:46 +000029 'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Thread', 'Barrier',
Benjamin Peterson7761b952011-08-02 13:05:47 -050030 'Timer', 'ThreadError', 'setprofile', 'settrace', 'local', 'stack_size']
Guido van Rossum7f5013a1998-04-09 22:01:42 +000031
Raymond Hettinger5cee47f2011-01-11 19:59:46 +000032# Rename some stuff so "from threading import *" is safe
Georg Brandl2067bfd2008-05-25 13:05:15 +000033_start_new_thread = _thread.start_new_thread
34_allocate_lock = _thread.allocate_lock
Antoine Pitrou7b476992013-09-07 23:38:37 +020035_set_sentinel = _thread._set_sentinel
Victor Stinner2a129742011-05-30 23:02:52 +020036get_ident = _thread.get_ident
Georg Brandl2067bfd2008-05-25 13:05:15 +000037ThreadError = _thread.error
Antoine Pitrou434736a2009-11-10 18:46:01 +000038try:
39 _CRLock = _thread.RLock
40except AttributeError:
41 _CRLock = None
Antoine Pitrou7c3e5772010-04-14 15:44:10 +000042TIMEOUT_MAX = _thread.TIMEOUT_MAX
Georg Brandl2067bfd2008-05-25 13:05:15 +000043del _thread
Guido van Rossum7f5013a1998-04-09 22:01:42 +000044
Guido van Rossum7f5013a1998-04-09 22:01:42 +000045
Jeremy Hyltonbfccb352003-06-29 16:58:41 +000046# Support for profile and trace hooks
47
48_profile_hook = None
49_trace_hook = None
50
51def setprofile(func):
Georg Brandlc30b59f2013-10-13 10:43:59 +020052 """Set a profile function for all threads started from the threading module.
53
54 The func will be passed to sys.setprofile() for each thread, before its
55 run() method is called.
56
57 """
Jeremy Hyltonbfccb352003-06-29 16:58:41 +000058 global _profile_hook
59 _profile_hook = func
Tim Petersd1b108b2003-06-29 17:24:17 +000060
Jeremy Hyltonbfccb352003-06-29 16:58:41 +000061def settrace(func):
Georg Brandlc30b59f2013-10-13 10:43:59 +020062 """Set a trace function for all threads started from the threading module.
63
64 The func will be passed to sys.settrace() for each thread, before its run()
65 method is called.
66
67 """
Jeremy Hyltonbfccb352003-06-29 16:58:41 +000068 global _trace_hook
69 _trace_hook = func
Guido van Rossum7f5013a1998-04-09 22:01:42 +000070
71# Synchronization classes
72
73Lock = _allocate_lock
74
Victor Stinner135b6d82012-03-03 01:32:57 +010075def RLock(*args, **kwargs):
Georg Brandlc30b59f2013-10-13 10:43:59 +020076 """Factory function that returns a new reentrant lock.
77
78 A reentrant lock must be released by the thread that acquired it. Once a
79 thread has acquired a reentrant lock, the same thread may acquire it again
80 without blocking; the thread must release it once for each time it has
81 acquired it.
82
83 """
Victor Stinner135b6d82012-03-03 01:32:57 +010084 if _CRLock is None:
85 return _PyRLock(*args, **kwargs)
Antoine Pitrou434736a2009-11-10 18:46:01 +000086 return _CRLock(*args, **kwargs)
Guido van Rossum7f5013a1998-04-09 22:01:42 +000087
Victor Stinner135b6d82012-03-03 01:32:57 +010088class _RLock:
Georg Brandlc30b59f2013-10-13 10:43:59 +020089 """This class implements reentrant lock objects.
90
91 A reentrant lock must be released by the thread that acquired it. Once a
92 thread has acquired a reentrant lock, the same thread may acquire it
93 again without blocking; the thread must release it once for each time it
94 has acquired it.
95
96 """
Tim Petersb90f89a2001-01-15 03:26:36 +000097
Victor Stinner135b6d82012-03-03 01:32:57 +010098 def __init__(self):
Guido van Rossumd0648992007-08-20 19:25:41 +000099 self._block = _allocate_lock()
100 self._owner = None
101 self._count = 0
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000102
103 def __repr__(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000104 owner = self._owner
Antoine Pitroub0872682009-11-09 16:08:16 +0000105 try:
106 owner = _active[owner].name
107 except KeyError:
108 pass
Raymond Hettinger62f4dad2014-05-25 18:22:35 -0700109 return "<%s %s.%s object owner=%r count=%d at %s>" % (
110 "locked" if self._block.locked() else "unlocked",
111 self.__class__.__module__,
112 self.__class__.__qualname__,
113 owner,
114 self._count,
115 hex(id(self))
116 )
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000117
Antoine Pitrou7c3e5772010-04-14 15:44:10 +0000118 def acquire(self, blocking=True, timeout=-1):
Georg Brandlc30b59f2013-10-13 10:43:59 +0200119 """Acquire a lock, blocking or non-blocking.
120
121 When invoked without arguments: if this thread already owns the lock,
122 increment the recursion level by one, and return immediately. Otherwise,
123 if another thread owns the lock, block until the lock is unlocked. Once
124 the lock is unlocked (not owned by any thread), then grab ownership, set
125 the recursion level to one, and return. If more than one thread is
126 blocked waiting until the lock is unlocked, only one at a time will be
127 able to grab ownership of the lock. There is no return value in this
128 case.
129
130 When invoked with the blocking argument set to true, do the same thing
131 as when called without arguments, and return true.
132
133 When invoked with the blocking argument set to false, do not block. If a
134 call without an argument would block, return false immediately;
135 otherwise, do the same thing as when called without arguments, and
136 return true.
137
138 When invoked with the floating-point timeout argument set to a positive
139 value, block for at most the number of seconds specified by timeout
140 and as long as the lock cannot be acquired. Return true if the lock has
141 been acquired, false if the timeout has elapsed.
142
143 """
Victor Stinner2a129742011-05-30 23:02:52 +0200144 me = get_ident()
Antoine Pitroub0872682009-11-09 16:08:16 +0000145 if self._owner == me:
Raymond Hettinger720da572013-03-10 15:13:35 -0700146 self._count += 1
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000147 return 1
Antoine Pitrou7c3e5772010-04-14 15:44:10 +0000148 rc = self._block.acquire(blocking, timeout)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000149 if rc:
Guido van Rossumd0648992007-08-20 19:25:41 +0000150 self._owner = me
151 self._count = 1
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000152 return rc
153
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000154 __enter__ = acquire
155
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000156 def release(self):
Georg Brandlc30b59f2013-10-13 10:43:59 +0200157 """Release a lock, decrementing the recursion level.
158
159 If after the decrement it is zero, reset the lock to unlocked (not owned
160 by any thread), and if any other threads are blocked waiting for the
161 lock to become unlocked, allow exactly one of them to proceed. If after
162 the decrement the recursion level is still nonzero, the lock remains
163 locked and owned by the calling thread.
164
165 Only call this method when the calling thread owns the lock. A
166 RuntimeError is raised if this method is called when the lock is
167 unlocked.
168
169 There is no return value.
170
171 """
Victor Stinner2a129742011-05-30 23:02:52 +0200172 if self._owner != get_ident():
Georg Brandl495f7b52009-10-27 15:28:25 +0000173 raise RuntimeError("cannot release un-acquired lock")
Guido van Rossumd0648992007-08-20 19:25:41 +0000174 self._count = count = self._count - 1
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000175 if not count:
Guido van Rossumd0648992007-08-20 19:25:41 +0000176 self._owner = None
177 self._block.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000178
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000179 def __exit__(self, t, v, tb):
180 self.release()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000181
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000182 # Internal methods used by condition variables
183
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000184 def _acquire_restore(self, state):
Guido van Rossumd0648992007-08-20 19:25:41 +0000185 self._block.acquire()
186 self._count, self._owner = state
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000187
188 def _release_save(self):
Victor Stinnerc2824d42011-04-24 23:41:33 +0200189 if self._count == 0:
190 raise RuntimeError("cannot release un-acquired lock")
Guido van Rossumd0648992007-08-20 19:25:41 +0000191 count = self._count
192 self._count = 0
193 owner = self._owner
194 self._owner = None
195 self._block.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000196 return (count, owner)
197
198 def _is_owned(self):
Victor Stinner2a129742011-05-30 23:02:52 +0200199 return self._owner == get_ident()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000200
Antoine Pitrou434736a2009-11-10 18:46:01 +0000201_PyRLock = _RLock
202
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000203
Victor Stinner135b6d82012-03-03 01:32:57 +0100204class Condition:
Georg Brandlc30b59f2013-10-13 10:43:59 +0200205 """Class that implements a condition variable.
206
207 A condition variable allows one or more threads to wait until they are
208 notified by another thread.
209
210 If the lock argument is given and not None, it must be a Lock or RLock
211 object, and it is used as the underlying lock. Otherwise, a new RLock object
212 is created and used as the underlying lock.
213
214 """
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000215
Victor Stinner135b6d82012-03-03 01:32:57 +0100216 def __init__(self, lock=None):
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000217 if lock is None:
218 lock = RLock()
Guido van Rossumd0648992007-08-20 19:25:41 +0000219 self._lock = lock
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000220 # Export the lock's acquire() and release() methods
221 self.acquire = lock.acquire
222 self.release = lock.release
223 # If the lock defines _release_save() and/or _acquire_restore(),
224 # these override the default implementations (which just call
225 # release() and acquire() on the lock). Ditto for _is_owned().
226 try:
227 self._release_save = lock._release_save
228 except AttributeError:
229 pass
230 try:
231 self._acquire_restore = lock._acquire_restore
232 except AttributeError:
233 pass
234 try:
235 self._is_owned = lock._is_owned
236 except AttributeError:
237 pass
Raymond Hettingerec4b1742013-03-10 17:57:28 -0700238 self._waiters = _deque()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000239
Thomas Wouters477c8d52006-05-27 19:21:47 +0000240 def __enter__(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000241 return self._lock.__enter__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000242
Thomas Wouters477c8d52006-05-27 19:21:47 +0000243 def __exit__(self, *args):
Guido van Rossumd0648992007-08-20 19:25:41 +0000244 return self._lock.__exit__(*args)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000245
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000246 def __repr__(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000247 return "<Condition(%s, %d)>" % (self._lock, len(self._waiters))
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000248
249 def _release_save(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000250 self._lock.release() # No state to save
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000251
252 def _acquire_restore(self, x):
Guido van Rossumd0648992007-08-20 19:25:41 +0000253 self._lock.acquire() # Ignore saved state
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000254
255 def _is_owned(self):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000256 # Return True if lock is owned by current_thread.
Jeremy Hyltonaf7fde72002-08-14 17:43:59 +0000257 # This method is called only if __lock doesn't have _is_owned().
Guido van Rossumd0648992007-08-20 19:25:41 +0000258 if self._lock.acquire(0):
259 self._lock.release()
Tim Petersbc0e9102002-04-04 22:55:58 +0000260 return False
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000261 else:
Tim Petersbc0e9102002-04-04 22:55:58 +0000262 return True
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000263
264 def wait(self, timeout=None):
Georg Brandlc30b59f2013-10-13 10:43:59 +0200265 """Wait until notified or until a timeout occurs.
266
267 If the calling thread has not acquired the lock when this method is
268 called, a RuntimeError is raised.
269
270 This method releases the underlying lock, and then blocks until it is
271 awakened by a notify() or notify_all() call for the same condition
272 variable in another thread, or until the optional timeout occurs. Once
273 awakened or timed out, it re-acquires the lock and returns.
274
275 When the timeout argument is present and not None, it should be a
276 floating point number specifying a timeout for the operation in seconds
277 (or fractions thereof).
278
279 When the underlying lock is an RLock, it is not released using its
280 release() method, since this may not actually unlock the lock when it
281 was acquired multiple times recursively. Instead, an internal interface
282 of the RLock class is used, which really unlocks it even when it has
283 been recursively acquired several times. Another internal interface is
284 then used to restore the recursion level when the lock is reacquired.
285
286 """
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000287 if not self._is_owned():
Georg Brandl495f7b52009-10-27 15:28:25 +0000288 raise RuntimeError("cannot wait on un-acquired lock")
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000289 waiter = _allocate_lock()
290 waiter.acquire()
Guido van Rossumd0648992007-08-20 19:25:41 +0000291 self._waiters.append(waiter)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000292 saved_state = self._release_save()
Tim Petersc951bf92001-04-02 20:15:57 +0000293 try: # restore state no matter what (e.g., KeyboardInterrupt)
294 if timeout is None:
295 waiter.acquire()
Georg Brandlb9a43912010-10-28 09:03:20 +0000296 gotit = True
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000297 else:
Antoine Pitrou7c3e5772010-04-14 15:44:10 +0000298 if timeout > 0:
299 gotit = waiter.acquire(True, timeout)
300 else:
301 gotit = waiter.acquire(False)
Tim Petersc951bf92001-04-02 20:15:57 +0000302 if not gotit:
Tim Petersc951bf92001-04-02 20:15:57 +0000303 try:
Guido van Rossumd0648992007-08-20 19:25:41 +0000304 self._waiters.remove(waiter)
Tim Petersc951bf92001-04-02 20:15:57 +0000305 except ValueError:
306 pass
Georg Brandlb9a43912010-10-28 09:03:20 +0000307 return gotit
Tim Petersc951bf92001-04-02 20:15:57 +0000308 finally:
309 self._acquire_restore(saved_state)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000310
Kristján Valur Jónsson63315202010-11-18 12:46:39 +0000311 def wait_for(self, predicate, timeout=None):
Georg Brandlc30b59f2013-10-13 10:43:59 +0200312 """Wait until a condition evaluates to True.
313
314 predicate should be a callable which result will be interpreted as a
315 boolean value. A timeout may be provided giving the maximum time to
316 wait.
317
318 """
Kristján Valur Jónsson63315202010-11-18 12:46:39 +0000319 endtime = None
320 waittime = timeout
321 result = predicate()
322 while not result:
323 if waittime is not None:
324 if endtime is None:
325 endtime = _time() + waittime
326 else:
327 waittime = endtime - _time()
328 if waittime <= 0:
Kristján Valur Jónsson63315202010-11-18 12:46:39 +0000329 break
Kristján Valur Jónsson63315202010-11-18 12:46:39 +0000330 self.wait(waittime)
331 result = predicate()
Kristján Valur Jónsson63315202010-11-18 12:46:39 +0000332 return result
333
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000334 def notify(self, n=1):
Georg Brandlc30b59f2013-10-13 10:43:59 +0200335 """Wake up one or more threads waiting on this condition, if any.
336
337 If the calling thread has not acquired the lock when this method is
338 called, a RuntimeError is raised.
339
340 This method wakes up at most n of the threads waiting for the condition
341 variable; it is a no-op if no threads are waiting.
342
343 """
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000344 if not self._is_owned():
Georg Brandl495f7b52009-10-27 15:28:25 +0000345 raise RuntimeError("cannot notify on un-acquired lock")
Raymond Hettingerb65e5792013-03-10 20:34:16 -0700346 all_waiters = self._waiters
347 waiters_to_notify = _deque(_islice(all_waiters, n))
348 if not waiters_to_notify:
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000349 return
Raymond Hettingerb65e5792013-03-10 20:34:16 -0700350 for waiter in waiters_to_notify:
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000351 waiter.release()
352 try:
Raymond Hettingerb65e5792013-03-10 20:34:16 -0700353 all_waiters.remove(waiter)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000354 except ValueError:
355 pass
356
Benjamin Peterson672b8032008-06-11 19:14:14 +0000357 def notify_all(self):
Georg Brandlc30b59f2013-10-13 10:43:59 +0200358 """Wake up all threads waiting on this condition.
359
360 If the calling thread has not acquired the lock when this method
361 is called, a RuntimeError is raised.
362
363 """
Guido van Rossumd0648992007-08-20 19:25:41 +0000364 self.notify(len(self._waiters))
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000365
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000366 notifyAll = notify_all
367
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000368
Victor Stinner135b6d82012-03-03 01:32:57 +0100369class Semaphore:
Georg Brandlc30b59f2013-10-13 10:43:59 +0200370 """This class implements semaphore objects.
371
372 Semaphores manage a counter representing the number of release() calls minus
373 the number of acquire() calls, plus an initial value. The acquire() method
374 blocks if necessary until it can return without making the counter
375 negative. If not given, value defaults to 1.
376
377 """
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000378
Andrew M. Kuchling39d3bfc2000-02-29 00:10:24 +0000379 # After Tim Peters' semaphore class, but not quite the same (no maximum)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000380
Victor Stinner135b6d82012-03-03 01:32:57 +0100381 def __init__(self, value=1):
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000382 if value < 0:
383 raise ValueError("semaphore initial value must be >= 0")
Guido van Rossumd0648992007-08-20 19:25:41 +0000384 self._cond = Condition(Lock())
385 self._value = value
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000386
Antoine Pitrou0454af92010-04-17 23:51:58 +0000387 def acquire(self, blocking=True, timeout=None):
Georg Brandlc30b59f2013-10-13 10:43:59 +0200388 """Acquire a semaphore, decrementing the internal counter by one.
389
390 When invoked without arguments: if the internal counter is larger than
391 zero on entry, decrement it by one and return immediately. If it is zero
392 on entry, block, waiting until some other thread has called release() to
393 make it larger than zero. This is done with proper interlocking so that
394 if multiple acquire() calls are blocked, release() will wake exactly one
395 of them up. The implementation may pick one at random, so the order in
396 which blocked threads are awakened should not be relied on. There is no
397 return value in this case.
398
399 When invoked with blocking set to true, do the same thing as when called
400 without arguments, and return true.
401
402 When invoked with blocking set to false, do not block. If a call without
403 an argument would block, return false immediately; otherwise, do the
404 same thing as when called without arguments, and return true.
405
406 When invoked with a timeout other than None, it will block for at
407 most timeout seconds. If acquire does not complete successfully in
408 that interval, return false. Return true otherwise.
409
410 """
Antoine Pitrou0454af92010-04-17 23:51:58 +0000411 if not blocking and timeout is not None:
412 raise ValueError("can't specify timeout for non-blocking acquire")
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000413 rc = False
Antoine Pitrou0454af92010-04-17 23:51:58 +0000414 endtime = None
Serhiy Storchaka81a58552013-04-22 22:51:43 +0300415 with self._cond:
416 while self._value == 0:
417 if not blocking:
418 break
419 if timeout is not None:
420 if endtime is None:
421 endtime = _time() + timeout
422 else:
423 timeout = endtime - _time()
424 if timeout <= 0:
425 break
426 self._cond.wait(timeout)
427 else:
Serhiy Storchakab00b5962013-04-22 22:54:16 +0300428 self._value -= 1
Serhiy Storchaka81a58552013-04-22 22:51:43 +0300429 rc = True
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000430 return rc
431
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000432 __enter__ = acquire
433
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000434 def release(self):
Georg Brandlc30b59f2013-10-13 10:43:59 +0200435 """Release a semaphore, incrementing the internal counter by one.
436
437 When the counter is zero on entry and another thread is waiting for it
438 to become larger than zero again, wake up that thread.
439
440 """
Serhiy Storchaka81a58552013-04-22 22:51:43 +0300441 with self._cond:
Serhiy Storchakab00b5962013-04-22 22:54:16 +0300442 self._value += 1
Serhiy Storchaka81a58552013-04-22 22:51:43 +0300443 self._cond.notify()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000444
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000445 def __exit__(self, t, v, tb):
446 self.release()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000447
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000448
Éric Araujo0cdd4452011-07-28 00:28:28 +0200449class BoundedSemaphore(Semaphore):
Georg Brandlc30b59f2013-10-13 10:43:59 +0200450 """Implements a bounded semaphore.
451
452 A bounded semaphore checks to make sure its current value doesn't exceed its
453 initial value. If it does, ValueError is raised. In most situations
454 semaphores are used to guard resources with limited capacity.
455
456 If the semaphore is released too many times it's a sign of a bug. If not
457 given, value defaults to 1.
458
459 Like regular semaphores, bounded semaphores manage a counter representing
460 the number of release() calls minus the number of acquire() calls, plus an
461 initial value. The acquire() method blocks if necessary until it can return
462 without making the counter negative. If not given, value defaults to 1.
463
464 """
465
Victor Stinner135b6d82012-03-03 01:32:57 +0100466 def __init__(self, value=1):
467 Semaphore.__init__(self, value)
Skip Montanaroe428bb72001-08-20 20:27:58 +0000468 self._initial_value = value
469
470 def release(self):
Georg Brandlc30b59f2013-10-13 10:43:59 +0200471 """Release a semaphore, incrementing the internal counter by one.
472
473 When the counter is zero on entry and another thread is waiting for it
474 to become larger than zero again, wake up that thread.
475
476 If the number of releases exceeds the number of acquires,
477 raise a ValueError.
478
479 """
Tim Peters7634e1c2013-10-08 20:55:51 -0500480 with self._cond:
481 if self._value >= self._initial_value:
482 raise ValueError("Semaphore released too many times")
483 self._value += 1
484 self._cond.notify()
Skip Montanaroe428bb72001-08-20 20:27:58 +0000485
486
Victor Stinner135b6d82012-03-03 01:32:57 +0100487class Event:
Georg Brandlc30b59f2013-10-13 10:43:59 +0200488 """Class implementing event objects.
489
490 Events manage a flag that can be set to true with the set() method and reset
491 to false with the clear() method. The wait() method blocks until the flag is
492 true. The flag is initially false.
493
494 """
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000495
496 # After Tim Peters' event class (without is_posted())
497
Victor Stinner135b6d82012-03-03 01:32:57 +0100498 def __init__(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000499 self._cond = Condition(Lock())
500 self._flag = False
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000501
Gregory P. Smith9bd4a242011-01-04 18:33:38 +0000502 def _reset_internal_locks(self):
503 # private! called by Thread._reset_internal_locks by _after_fork()
504 self._cond.__init__()
505
Benjamin Peterson672b8032008-06-11 19:14:14 +0000506 def is_set(self):
Georg Brandlc30b59f2013-10-13 10:43:59 +0200507 """Return true if and only if the internal flag is true."""
Guido van Rossumd0648992007-08-20 19:25:41 +0000508 return self._flag
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000509
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000510 isSet = is_set
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000511
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000512 def set(self):
Georg Brandlc30b59f2013-10-13 10:43:59 +0200513 """Set the internal flag to true.
514
515 All threads waiting for it to become true are awakened. Threads
516 that call wait() once the flag is true will not block at all.
517
518 """
Christian Heimes969fe572008-01-25 11:23:10 +0000519 self._cond.acquire()
520 try:
Guido van Rossumd0648992007-08-20 19:25:41 +0000521 self._flag = True
Benjamin Peterson672b8032008-06-11 19:14:14 +0000522 self._cond.notify_all()
Christian Heimes969fe572008-01-25 11:23:10 +0000523 finally:
524 self._cond.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000525
526 def clear(self):
Georg Brandlc30b59f2013-10-13 10:43:59 +0200527 """Reset the internal flag to false.
528
529 Subsequently, threads calling wait() will block until set() is called to
530 set the internal flag to true again.
531
532 """
Christian Heimes969fe572008-01-25 11:23:10 +0000533 self._cond.acquire()
534 try:
Guido van Rossumd0648992007-08-20 19:25:41 +0000535 self._flag = False
Christian Heimes969fe572008-01-25 11:23:10 +0000536 finally:
537 self._cond.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000538
539 def wait(self, timeout=None):
Georg Brandlc30b59f2013-10-13 10:43:59 +0200540 """Block until the internal flag is true.
541
542 If the internal flag is true on entry, return immediately. Otherwise,
543 block until another thread calls set() to set the flag to true, or until
544 the optional timeout occurs.
545
546 When the timeout argument is present and not None, it should be a
547 floating point number specifying a timeout for the operation in seconds
548 (or fractions thereof).
549
550 This method returns the internal flag on exit, so it will always return
551 True except if a timeout is given and the operation times out.
552
553 """
Christian Heimes969fe572008-01-25 11:23:10 +0000554 self._cond.acquire()
555 try:
Charles-François Natalided03482012-01-07 18:24:56 +0100556 signaled = self._flag
557 if not signaled:
558 signaled = self._cond.wait(timeout)
559 return signaled
Christian Heimes969fe572008-01-25 11:23:10 +0000560 finally:
561 self._cond.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000562
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +0000563
564# A barrier class. Inspired in part by the pthread_barrier_* api and
565# the CyclicBarrier class from Java. See
566# http://sourceware.org/pthreads-win32/manual/pthread_barrier_init.html and
567# http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/
568# CyclicBarrier.html
569# for information.
570# We maintain two main states, 'filling' and 'draining' enabling the barrier
571# to be cyclic. Threads are not allowed into it until it has fully drained
572# since the previous cycle. In addition, a 'resetting' state exists which is
573# similar to 'draining' except that threads leave with a BrokenBarrierError,
Ezio Melottie130a522011-10-19 10:58:56 +0300574# and a 'broken' state in which all threads get the exception.
Victor Stinner135b6d82012-03-03 01:32:57 +0100575class Barrier:
Georg Brandlc30b59f2013-10-13 10:43:59 +0200576 """Implements a Barrier.
577
578 Useful for synchronizing a fixed number of threads at known synchronization
579 points. Threads block on 'wait()' and are simultaneously once they have all
580 made that call.
581
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +0000582 """
Georg Brandlc30b59f2013-10-13 10:43:59 +0200583
Victor Stinner135b6d82012-03-03 01:32:57 +0100584 def __init__(self, parties, action=None, timeout=None):
Georg Brandlc30b59f2013-10-13 10:43:59 +0200585 """Create a barrier, initialised to 'parties' threads.
586
587 'action' is a callable which, when supplied, will be called by one of
588 the threads after they have all entered the barrier and just prior to
589 releasing them all. If a 'timeout' is provided, it is uses as the
590 default for all subsequent 'wait()' calls.
591
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +0000592 """
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +0000593 self._cond = Condition(Lock())
594 self._action = action
595 self._timeout = timeout
596 self._parties = parties
597 self._state = 0 #0 filling, 1, draining, -1 resetting, -2 broken
598 self._count = 0
599
600 def wait(self, timeout=None):
Georg Brandlc30b59f2013-10-13 10:43:59 +0200601 """Wait for the barrier.
602
603 When the specified number of threads have started waiting, they are all
604 simultaneously awoken. If an 'action' was provided for the barrier, one
605 of the threads will have executed that callback prior to returning.
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +0000606 Returns an individual index number from 0 to 'parties-1'.
Georg Brandlc30b59f2013-10-13 10:43:59 +0200607
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +0000608 """
609 if timeout is None:
610 timeout = self._timeout
611 with self._cond:
612 self._enter() # Block while the barrier drains.
613 index = self._count
614 self._count += 1
615 try:
616 if index + 1 == self._parties:
617 # We release the barrier
618 self._release()
619 else:
620 # We wait until someone releases us
621 self._wait(timeout)
622 return index
623 finally:
624 self._count -= 1
625 # Wake up any threads waiting for barrier to drain.
626 self._exit()
627
628 # Block until the barrier is ready for us, or raise an exception
629 # if it is broken.
630 def _enter(self):
631 while self._state in (-1, 1):
632 # It is draining or resetting, wait until done
633 self._cond.wait()
634 #see if the barrier is in a broken state
635 if self._state < 0:
636 raise BrokenBarrierError
637 assert self._state == 0
638
639 # Optionally run the 'action' and release the threads waiting
640 # in the barrier.
641 def _release(self):
642 try:
643 if self._action:
644 self._action()
645 # enter draining state
646 self._state = 1
647 self._cond.notify_all()
648 except:
649 #an exception during the _action handler. Break and reraise
650 self._break()
651 raise
652
653 # Wait in the barrier until we are relased. Raise an exception
654 # if the barrier is reset or broken.
655 def _wait(self, timeout):
Kristján Valur Jónsson63315202010-11-18 12:46:39 +0000656 if not self._cond.wait_for(lambda : self._state != 0, timeout):
657 #timed out. Break the barrier
658 self._break()
659 raise BrokenBarrierError
660 if self._state < 0:
661 raise BrokenBarrierError
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +0000662 assert self._state == 1
663
664 # If we are the last thread to exit the barrier, signal any threads
665 # waiting for the barrier to drain.
666 def _exit(self):
667 if self._count == 0:
668 if self._state in (-1, 1):
669 #resetting or draining
670 self._state = 0
671 self._cond.notify_all()
672
673 def reset(self):
Georg Brandlc30b59f2013-10-13 10:43:59 +0200674 """Reset the barrier to the initial state.
675
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +0000676 Any threads currently waiting will get the BrokenBarrier exception
677 raised.
Georg Brandlc30b59f2013-10-13 10:43:59 +0200678
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +0000679 """
680 with self._cond:
681 if self._count > 0:
682 if self._state == 0:
683 #reset the barrier, waking up threads
684 self._state = -1
685 elif self._state == -2:
686 #was broken, set it to reset state
687 #which clears when the last thread exits
688 self._state = -1
689 else:
690 self._state = 0
691 self._cond.notify_all()
692
693 def abort(self):
Georg Brandlc30b59f2013-10-13 10:43:59 +0200694 """Place the barrier into a 'broken' state.
695
696 Useful in case of error. Any currently waiting threads and threads
697 attempting to 'wait()' will have BrokenBarrierError raised.
698
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +0000699 """
700 with self._cond:
701 self._break()
702
703 def _break(self):
704 # An internal error was detected. The barrier is set to
705 # a broken state all parties awakened.
706 self._state = -2
707 self._cond.notify_all()
708
709 @property
710 def parties(self):
Georg Brandlc30b59f2013-10-13 10:43:59 +0200711 """Return the number of threads required to trip the barrier."""
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +0000712 return self._parties
713
714 @property
715 def n_waiting(self):
Georg Brandlc30b59f2013-10-13 10:43:59 +0200716 """Return the number of threads currently waiting at the barrier."""
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +0000717 # We don't need synchronization here since this is an ephemeral result
718 # anyway. It returns the correct value in the steady state.
719 if self._state == 0:
720 return self._count
721 return 0
722
723 @property
724 def broken(self):
Georg Brandlc30b59f2013-10-13 10:43:59 +0200725 """Return True if the barrier is in a broken state."""
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +0000726 return self._state == -2
727
Georg Brandlc30b59f2013-10-13 10:43:59 +0200728# exception raised by the Barrier class
729class BrokenBarrierError(RuntimeError):
730 pass
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +0000731
732
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000733# Helper to generate new thread names
734_counter = 0
735def _newname(template="Thread-%d"):
736 global _counter
Raymond Hettinger720da572013-03-10 15:13:35 -0700737 _counter += 1
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000738 return template % _counter
739
740# Active thread administration
741_active_limbo_lock = _allocate_lock()
Tim Peters711906e2005-01-08 07:30:42 +0000742_active = {} # maps thread id to Thread object
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000743_limbo = {}
Antoine Pitrouc081c0c2011-07-15 22:12:24 +0200744_dangling = WeakSet()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000745
746# Main class for threads
747
Victor Stinner135b6d82012-03-03 01:32:57 +0100748class Thread:
Georg Brandlc30b59f2013-10-13 10:43:59 +0200749 """A class that represents a thread of control.
750
751 This class can be safely subclassed in a limited fashion. There are two ways
752 to specify the activity: by passing a callable object to the constructor, or
753 by overriding the run() method in a subclass.
754
755 """
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000756
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000757 __initialized = False
Brett Cannoncc4e9352004-07-03 03:52:35 +0000758 # Need to store a reference to sys.exc_info for printing
759 # out exceptions when a thread tries to use a global var. during interp.
760 # shutdown and thus raises an exception about trying to perform some
761 # operation on/with a NoneType
762 __exc_info = _sys.exc_info
Christian Heimesbbe741d2008-03-28 10:53:29 +0000763 # Keep sys.exc_clear too to clear the exception just before
764 # allowing .join() to return.
765 #XXX __exc_clear = _sys.exc_clear
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000766
767 def __init__(self, group=None, target=None, name=None,
Victor Stinner135b6d82012-03-03 01:32:57 +0100768 args=(), kwargs=None, *, daemon=None):
Georg Brandlc30b59f2013-10-13 10:43:59 +0200769 """This constructor should always be called with keyword arguments. Arguments are:
770
771 *group* should be None; reserved for future extension when a ThreadGroup
772 class is implemented.
773
774 *target* is the callable object to be invoked by the run()
775 method. Defaults to None, meaning nothing is called.
776
777 *name* is the thread name. By default, a unique name is constructed of
778 the form "Thread-N" where N is a small decimal number.
779
780 *args* is the argument tuple for the target invocation. Defaults to ().
781
782 *kwargs* is a dictionary of keyword arguments for the target
783 invocation. Defaults to {}.
784
785 If a subclass overrides the constructor, it must make sure to invoke
786 the base class constructor (Thread.__init__()) before doing anything
787 else to the thread.
788
789 """
Guido van Rossum5a43e1a1998-06-09 19:04:26 +0000790 assert group is None, "group argument must be None for now"
Georg Brandla4a8b822005-07-15 09:13:21 +0000791 if kwargs is None:
792 kwargs = {}
Guido van Rossumd0648992007-08-20 19:25:41 +0000793 self._target = target
794 self._name = str(name or _newname())
795 self._args = args
796 self._kwargs = kwargs
Antoine Pitrou0bd4deb2011-02-25 22:07:43 +0000797 if daemon is not None:
798 self._daemonic = daemon
799 else:
800 self._daemonic = current_thread().daemon
Georg Brandl0c77a822008-06-10 16:37:50 +0000801 self._ident = None
Antoine Pitrou7b476992013-09-07 23:38:37 +0200802 self._tstate_lock = None
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000803 self._started = Event()
Tim Petersc363a232013-09-08 18:44:40 -0500804 self._is_stopped = False
Guido van Rossumd0648992007-08-20 19:25:41 +0000805 self._initialized = True
Brett Cannoncc4e9352004-07-03 03:52:35 +0000806 # sys.stderr is not stored in the class like
807 # sys.exc_info since it can be changed between instances
Guido van Rossumd0648992007-08-20 19:25:41 +0000808 self._stderr = _sys.stderr
Antoine Pitrou5da7e792013-09-08 13:19:06 +0200809 # For debugging and _after_fork()
Antoine Pitrouc081c0c2011-07-15 22:12:24 +0200810 _dangling.add(self)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000811
Antoine Pitrou7b476992013-09-07 23:38:37 +0200812 def _reset_internal_locks(self, is_alive):
Gregory P. Smith9bd4a242011-01-04 18:33:38 +0000813 # private! Called by _after_fork() to reset our internal locks as
814 # they may be in an invalid state leading to a deadlock or crash.
Gregory P. Smith9bd4a242011-01-04 18:33:38 +0000815 self._started._reset_internal_locks()
Antoine Pitrou7b476992013-09-07 23:38:37 +0200816 if is_alive:
817 self._set_tstate_lock()
818 else:
819 # The thread isn't alive after fork: it doesn't have a tstate
820 # anymore.
Tim Petersb5e9ac92013-09-09 14:41:50 -0500821 self._is_stopped = True
Antoine Pitrou7b476992013-09-07 23:38:37 +0200822 self._tstate_lock = None
Gregory P. Smith9bd4a242011-01-04 18:33:38 +0000823
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000824 def __repr__(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000825 assert self._initialized, "Thread.__init__() was not called"
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000826 status = "initial"
Benjamin Peterson672b8032008-06-11 19:14:14 +0000827 if self._started.is_set():
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000828 status = "started"
Tim Peters72460fa2013-09-09 18:48:24 -0500829 self.is_alive() # easy way to get ._is_stopped set when appropriate
Tim Petersc363a232013-09-08 18:44:40 -0500830 if self._is_stopped:
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000831 status = "stopped"
Guido van Rossumd0648992007-08-20 19:25:41 +0000832 if self._daemonic:
Georg Brandl0c77a822008-06-10 16:37:50 +0000833 status += " daemon"
834 if self._ident is not None:
835 status += " %s" % self._ident
Guido van Rossumd0648992007-08-20 19:25:41 +0000836 return "<%s(%s, %s)>" % (self.__class__.__name__, self._name, status)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000837
838 def start(self):
Georg Brandlc30b59f2013-10-13 10:43:59 +0200839 """Start the thread's activity.
840
841 It must be called at most once per thread object. It arranges for the
842 object's run() method to be invoked in a separate thread of control.
843
844 This method will raise a RuntimeError if called more than once on the
845 same thread object.
846
847 """
Guido van Rossumd0648992007-08-20 19:25:41 +0000848 if not self._initialized:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000849 raise RuntimeError("thread.__init__() not called")
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000850
Benjamin Peterson672b8032008-06-11 19:14:14 +0000851 if self._started.is_set():
Senthil Kumaranfdd4d0f2010-04-06 03:30:18 +0000852 raise RuntimeError("threads can only be started once")
Benjamin Petersond23f8222009-04-05 19:13:16 +0000853 with _active_limbo_lock:
854 _limbo[self] = self
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000855 try:
856 _start_new_thread(self._bootstrap, ())
857 except Exception:
858 with _active_limbo_lock:
859 del _limbo[self]
860 raise
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000861 self._started.wait()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000862
863 def run(self):
Georg Brandlc30b59f2013-10-13 10:43:59 +0200864 """Method representing the thread's activity.
865
866 You may override this method in a subclass. The standard run() method
867 invokes the callable object passed to the object's constructor as the
868 target argument, if any, with sequential and keyword arguments taken
869 from the args and kwargs arguments, respectively.
870
871 """
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000872 try:
873 if self._target:
874 self._target(*self._args, **self._kwargs)
875 finally:
876 # Avoid a refcycle if the thread is running a function with
877 # an argument that has a member that points to the thread.
878 del self._target, self._args, self._kwargs
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000879
Guido van Rossumd0648992007-08-20 19:25:41 +0000880 def _bootstrap(self):
Guido van Rossum61e21b52007-08-20 19:06:03 +0000881 # Wrapper around the real bootstrap code that ignores
882 # exceptions during interpreter cleanup. Those typically
883 # happen when a daemon thread wakes up at an unfortunate
884 # moment, finds the world around it destroyed, and raises some
885 # random exception *** while trying to report the exception in
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000886 # _bootstrap_inner() below ***. Those random exceptions
Guido van Rossum61e21b52007-08-20 19:06:03 +0000887 # don't help anybody, and they confuse users, so we suppress
888 # them. We suppress them only when it appears that the world
889 # indeed has already been destroyed, so that exceptions in
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000890 # _bootstrap_inner() during normal business hours are properly
Guido van Rossum61e21b52007-08-20 19:06:03 +0000891 # reported. Also, we only suppress them for daemonic threads;
892 # if a non-daemonic encounters this, something else is wrong.
893 try:
Guido van Rossumd0648992007-08-20 19:25:41 +0000894 self._bootstrap_inner()
Guido van Rossum61e21b52007-08-20 19:06:03 +0000895 except:
Guido van Rossumd0648992007-08-20 19:25:41 +0000896 if self._daemonic and _sys is None:
Guido van Rossum61e21b52007-08-20 19:06:03 +0000897 return
898 raise
899
Benjamin Petersond23f8222009-04-05 19:13:16 +0000900 def _set_ident(self):
Victor Stinner2a129742011-05-30 23:02:52 +0200901 self._ident = get_ident()
Benjamin Petersond23f8222009-04-05 19:13:16 +0000902
Antoine Pitrou7b476992013-09-07 23:38:37 +0200903 def _set_tstate_lock(self):
904 """
905 Set a lock object which will be released by the interpreter when
906 the underlying thread state (see pystate.h) gets deleted.
907 """
908 self._tstate_lock = _set_sentinel()
909 self._tstate_lock.acquire()
910
Guido van Rossumd0648992007-08-20 19:25:41 +0000911 def _bootstrap_inner(self):
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000912 try:
Benjamin Petersond23f8222009-04-05 19:13:16 +0000913 self._set_ident()
Antoine Pitrou7b476992013-09-07 23:38:37 +0200914 self._set_tstate_lock()
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000915 self._started.set()
Benjamin Petersond23f8222009-04-05 19:13:16 +0000916 with _active_limbo_lock:
917 _active[self._ident] = self
918 del _limbo[self]
Jeremy Hyltonbfccb352003-06-29 16:58:41 +0000919
920 if _trace_hook:
Jeremy Hyltonbfccb352003-06-29 16:58:41 +0000921 _sys.settrace(_trace_hook)
922 if _profile_hook:
Jeremy Hyltonbfccb352003-06-29 16:58:41 +0000923 _sys.setprofile(_profile_hook)
Tim Petersd1b108b2003-06-29 17:24:17 +0000924
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000925 try:
926 self.run()
927 except SystemExit:
Victor Stinner135b6d82012-03-03 01:32:57 +0100928 pass
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000929 except:
Brett Cannoncc4e9352004-07-03 03:52:35 +0000930 # If sys.stderr is no more (most likely from interpreter
Guido van Rossumd0648992007-08-20 19:25:41 +0000931 # shutdown) use self._stderr. Otherwise still use sys (as in
Brett Cannoncc4e9352004-07-03 03:52:35 +0000932 # _sys) in case sys.stderr was redefined since the creation of
933 # self.
934 if _sys:
935 _sys.stderr.write("Exception in thread %s:\n%s\n" %
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000936 (self.name, _format_exc()))
Brett Cannoncc4e9352004-07-03 03:52:35 +0000937 else:
938 # Do the best job possible w/o a huge amt. of code to
939 # approximate a traceback (code ideas from
940 # Lib/traceback.py)
Guido van Rossumd0648992007-08-20 19:25:41 +0000941 exc_type, exc_value, exc_tb = self._exc_info()
Brett Cannoncc4e9352004-07-03 03:52:35 +0000942 try:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000943 print((
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000944 "Exception in thread " + self.name +
Guido van Rossumd0648992007-08-20 19:25:41 +0000945 " (most likely raised during interpreter shutdown):"), file=self._stderr)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000946 print((
Guido van Rossumd0648992007-08-20 19:25:41 +0000947 "Traceback (most recent call last):"), file=self._stderr)
Brett Cannoncc4e9352004-07-03 03:52:35 +0000948 while exc_tb:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000949 print((
Brett Cannoncc4e9352004-07-03 03:52:35 +0000950 ' File "%s", line %s, in %s' %
951 (exc_tb.tb_frame.f_code.co_filename,
952 exc_tb.tb_lineno,
Guido van Rossumd0648992007-08-20 19:25:41 +0000953 exc_tb.tb_frame.f_code.co_name)), file=self._stderr)
Brett Cannoncc4e9352004-07-03 03:52:35 +0000954 exc_tb = exc_tb.tb_next
Guido van Rossumd0648992007-08-20 19:25:41 +0000955 print(("%s: %s" % (exc_type, exc_value)), file=self._stderr)
Brett Cannoncc4e9352004-07-03 03:52:35 +0000956 # Make sure that exc_tb gets deleted since it is a memory
957 # hog; deleting everything else is just for thoroughness
958 finally:
959 del exc_type, exc_value, exc_tb
Christian Heimesbbe741d2008-03-28 10:53:29 +0000960 finally:
961 # Prevent a race in
962 # test_threading.test_no_refcycle_through_target when
963 # the exception keeps the target alive past when we
964 # assert that it's dead.
965 #XXX self.__exc_clear()
966 pass
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000967 finally:
Christian Heimes1af737c2008-01-23 08:24:23 +0000968 with _active_limbo_lock:
Christian Heimes1af737c2008-01-23 08:24:23 +0000969 try:
Georg Brandl0c77a822008-06-10 16:37:50 +0000970 # We don't call self._delete() because it also
Christian Heimes1af737c2008-01-23 08:24:23 +0000971 # grabs _active_limbo_lock.
Victor Stinner2a129742011-05-30 23:02:52 +0200972 del _active[get_ident()]
Christian Heimes1af737c2008-01-23 08:24:23 +0000973 except:
974 pass
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000975
Guido van Rossumd0648992007-08-20 19:25:41 +0000976 def _stop(self):
Tim Petersb5e9ac92013-09-09 14:41:50 -0500977 # After calling ._stop(), .is_alive() returns False and .join() returns
978 # immediately. ._tstate_lock must be released before calling ._stop().
979 #
980 # Normal case: C code at the end of the thread's life
981 # (release_sentinel in _threadmodule.c) releases ._tstate_lock, and
982 # that's detected by our ._wait_for_tstate_lock(), called by .join()
983 # and .is_alive(). Any number of threads _may_ call ._stop()
984 # simultaneously (for example, if multiple threads are blocked in
985 # .join() calls), and they're not serialized. That's harmless -
986 # they'll just make redundant rebindings of ._is_stopped and
987 # ._tstate_lock. Obscure: we rebind ._tstate_lock last so that the
988 # "assert self._is_stopped" in ._wait_for_tstate_lock() always works
989 # (the assert is executed only if ._tstate_lock is None).
990 #
991 # Special case: _main_thread releases ._tstate_lock via this
992 # module's _shutdown() function.
993 lock = self._tstate_lock
994 if lock is not None:
995 assert not lock.locked()
Tim Peters78755232013-09-09 13:47:16 -0500996 self._is_stopped = True
997 self._tstate_lock = None
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000998
Guido van Rossumd0648992007-08-20 19:25:41 +0000999 def _delete(self):
Tim Peters21429932004-07-21 03:36:52 +00001000 "Remove current thread from the dict of currently running threads."
Brett Cannon8b3d92a2004-07-21 02:21:58 +00001001
Georg Brandl2067bfd2008-05-25 13:05:15 +00001002 # Notes about running with _dummy_thread:
Tim Peters21429932004-07-21 03:36:52 +00001003 #
Georg Brandl2067bfd2008-05-25 13:05:15 +00001004 # Must take care to not raise an exception if _dummy_thread is being
Tim Peters21429932004-07-21 03:36:52 +00001005 # used (and thus this module is being used as an instance of
Georg Brandl2067bfd2008-05-25 13:05:15 +00001006 # dummy_threading). _dummy_thread.get_ident() always returns -1 since
1007 # there is only one thread if _dummy_thread is being used. Thus
Tim Peters21429932004-07-21 03:36:52 +00001008 # len(_active) is always <= 1 here, and any Thread instance created
1009 # overwrites the (if any) thread currently registered in _active.
1010 #
1011 # An instance of _MainThread is always created by 'threading'. This
1012 # gets overwritten the instant an instance of Thread is created; both
Georg Brandl2067bfd2008-05-25 13:05:15 +00001013 # threads return -1 from _dummy_thread.get_ident() and thus have the
Tim Peters21429932004-07-21 03:36:52 +00001014 # same key in the dict. So when the _MainThread instance created by
1015 # 'threading' tries to clean itself up when atexit calls this method
1016 # it gets a KeyError if another Thread instance was created.
1017 #
1018 # This all means that KeyError from trying to delete something from
1019 # _active if dummy_threading is being used is a red herring. But
1020 # since it isn't if dummy_threading is *not* being used then don't
1021 # hide the exception.
Brett Cannon8b3d92a2004-07-21 02:21:58 +00001022
Christian Heimes969fe572008-01-25 11:23:10 +00001023 try:
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +00001024 with _active_limbo_lock:
Victor Stinner2a129742011-05-30 23:02:52 +02001025 del _active[get_ident()]
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +00001026 # There must not be any python code between the previous line
1027 # and after the lock is released. Otherwise a tracing function
1028 # could try to acquire the lock again in the same thread, (in
Benjamin Peterson672b8032008-06-11 19:14:14 +00001029 # current_thread()), and would block.
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +00001030 except KeyError:
1031 if 'dummy_threading' not in _sys.modules:
1032 raise
Guido van Rossum7f5013a1998-04-09 22:01:42 +00001033
1034 def join(self, timeout=None):
Georg Brandlc30b59f2013-10-13 10:43:59 +02001035 """Wait until the thread terminates.
1036
1037 This blocks the calling thread until the thread whose join() method is
1038 called terminates -- either normally or through an unhandled exception
1039 or until the optional timeout occurs.
1040
1041 When the timeout argument is present and not None, it should be a
1042 floating point number specifying a timeout for the operation in seconds
1043 (or fractions thereof). As join() always returns None, you must call
1044 isAlive() after join() to decide whether a timeout happened -- if the
1045 thread is still alive, the join() call timed out.
1046
1047 When the timeout argument is not present or None, the operation will
1048 block until the thread terminates.
1049
1050 A thread can be join()ed many times.
1051
1052 join() raises a RuntimeError if an attempt is made to join the current
1053 thread as that would cause a deadlock. It is also an error to join() a
1054 thread before it has been started and attempts to do so raises the same
1055 exception.
1056
1057 """
Guido van Rossumd0648992007-08-20 19:25:41 +00001058 if not self._initialized:
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001059 raise RuntimeError("Thread.__init__() not called")
Benjamin Peterson672b8032008-06-11 19:14:14 +00001060 if not self._started.is_set():
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001061 raise RuntimeError("cannot join thread before it is started")
Benjamin Peterson672b8032008-06-11 19:14:14 +00001062 if self is current_thread():
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001063 raise RuntimeError("cannot join current thread")
Tim Peterse5bb0bf2013-10-25 20:46:51 -05001064
Tim Petersc363a232013-09-08 18:44:40 -05001065 if timeout is None:
1066 self._wait_for_tstate_lock()
Tim Peters7bad39f2013-10-25 22:33:52 -05001067 else:
1068 # the behavior of a negative timeout isn't documented, but
Tim Petersa577f1e2013-10-26 11:56:16 -05001069 # historically .join(timeout=x) for x<0 has acted as if timeout=0
Tim Peters7bad39f2013-10-25 22:33:52 -05001070 self._wait_for_tstate_lock(timeout=max(timeout, 0))
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001071
Tim Petersc363a232013-09-08 18:44:40 -05001072 def _wait_for_tstate_lock(self, block=True, timeout=-1):
Antoine Pitrou7b476992013-09-07 23:38:37 +02001073 # Issue #18808: wait for the thread state to be gone.
Tim Petersc363a232013-09-08 18:44:40 -05001074 # At the end of the thread's life, after all knowledge of the thread
1075 # is removed from C data structures, C code releases our _tstate_lock.
1076 # This method passes its arguments to _tstate_lock.aquire().
1077 # If the lock is acquired, the C code is done, and self._stop() is
1078 # called. That sets ._is_stopped to True, and ._tstate_lock to None.
Antoine Pitrou7b476992013-09-07 23:38:37 +02001079 lock = self._tstate_lock
Tim Petersc363a232013-09-08 18:44:40 -05001080 if lock is None: # already determined that the C code is done
1081 assert self._is_stopped
1082 elif lock.acquire(block, timeout):
Antoine Pitrou7b476992013-09-07 23:38:37 +02001083 lock.release()
Tim Petersc363a232013-09-08 18:44:40 -05001084 self._stop()
Guido van Rossum7f5013a1998-04-09 22:01:42 +00001085
Benjamin Petersonfdbea962008-08-18 17:33:47 +00001086 @property
1087 def name(self):
Georg Brandlc30b59f2013-10-13 10:43:59 +02001088 """A string used for identification purposes only.
1089
1090 It has no semantics. Multiple threads may be given the same name. The
1091 initial name is set by the constructor.
1092
1093 """
Guido van Rossumd0648992007-08-20 19:25:41 +00001094 assert self._initialized, "Thread.__init__() not called"
1095 return self._name
Guido van Rossum7f5013a1998-04-09 22:01:42 +00001096
Benjamin Petersonfdbea962008-08-18 17:33:47 +00001097 @name.setter
1098 def name(self, name):
Guido van Rossumd0648992007-08-20 19:25:41 +00001099 assert self._initialized, "Thread.__init__() not called"
1100 self._name = str(name)
Guido van Rossum7f5013a1998-04-09 22:01:42 +00001101
Benjamin Peterson773c17b2008-08-18 16:45:31 +00001102 @property
1103 def ident(self):
Georg Brandlc30b59f2013-10-13 10:43:59 +02001104 """Thread identifier of this thread or None if it has not been started.
1105
1106 This is a nonzero integer. See the thread.get_ident() function. Thread
1107 identifiers may be recycled when a thread exits and another thread is
1108 created. The identifier is available even after the thread has exited.
1109
1110 """
Georg Brandl0c77a822008-06-10 16:37:50 +00001111 assert self._initialized, "Thread.__init__() not called"
1112 return self._ident
1113
Benjamin Peterson672b8032008-06-11 19:14:14 +00001114 def is_alive(self):
Georg Brandlc30b59f2013-10-13 10:43:59 +02001115 """Return whether the thread is alive.
1116
1117 This method returns True just before the run() method starts until just
1118 after the run() method terminates. The module function enumerate()
1119 returns a list of all alive threads.
1120
1121 """
Guido van Rossumd0648992007-08-20 19:25:41 +00001122 assert self._initialized, "Thread.__init__() not called"
Tim Petersc363a232013-09-08 18:44:40 -05001123 if self._is_stopped or not self._started.is_set():
Antoine Pitrou7b476992013-09-07 23:38:37 +02001124 return False
Antoine Pitrou7b476992013-09-07 23:38:37 +02001125 self._wait_for_tstate_lock(False)
Tim Petersc363a232013-09-08 18:44:40 -05001126 return not self._is_stopped
Tim Petersb90f89a2001-01-15 03:26:36 +00001127
Benjamin Petersonb3085c92008-09-01 23:09:31 +00001128 isAlive = is_alive
Benjamin Petersonf0923f52008-08-18 22:10:13 +00001129
Benjamin Petersonfdbea962008-08-18 17:33:47 +00001130 @property
1131 def daemon(self):
Georg Brandlc30b59f2013-10-13 10:43:59 +02001132 """A boolean value indicating whether this thread is a daemon thread.
1133
1134 This must be set before start() is called, otherwise RuntimeError is
1135 raised. Its initial value is inherited from the creating thread; the
1136 main thread is not a daemon thread and therefore all threads created in
1137 the main thread default to daemon = False.
1138
1139 The entire Python program exits when no alive non-daemon threads are
1140 left.
1141
1142 """
Guido van Rossumd0648992007-08-20 19:25:41 +00001143 assert self._initialized, "Thread.__init__() not called"
1144 return self._daemonic
Guido van Rossum7f5013a1998-04-09 22:01:42 +00001145
Benjamin Petersonfdbea962008-08-18 17:33:47 +00001146 @daemon.setter
1147 def daemon(self, daemonic):
Guido van Rossumd0648992007-08-20 19:25:41 +00001148 if not self._initialized:
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001149 raise RuntimeError("Thread.__init__() not called")
Benjamin Peterson672b8032008-06-11 19:14:14 +00001150 if self._started.is_set():
Antoine Pitrou10959072014-03-17 18:22:41 +01001151 raise RuntimeError("cannot set daemon status of active thread")
Guido van Rossumd0648992007-08-20 19:25:41 +00001152 self._daemonic = daemonic
Guido van Rossum7f5013a1998-04-09 22:01:42 +00001153
Benjamin Peterson6640d722008-08-18 18:16:46 +00001154 def isDaemon(self):
1155 return self.daemon
1156
1157 def setDaemon(self, daemonic):
1158 self.daemon = daemonic
1159
1160 def getName(self):
1161 return self.name
1162
1163 def setName(self, name):
1164 self.name = name
1165
Martin v. Löwis44f86962001-09-05 13:44:54 +00001166# The timer class was contributed by Itamar Shtull-Trauring
1167
Éric Araujo0cdd4452011-07-28 00:28:28 +02001168class Timer(Thread):
Martin v. Löwis44f86962001-09-05 13:44:54 +00001169 """Call a function after a specified number of seconds:
Tim Petersb64bec32001-09-18 02:26:39 +00001170
Georg Brandlc30b59f2013-10-13 10:43:59 +02001171 t = Timer(30.0, f, args=None, kwargs=None)
1172 t.start()
1173 t.cancel() # stop the timer's action if it's still waiting
1174
Martin v. Löwis44f86962001-09-05 13:44:54 +00001175 """
Tim Petersb64bec32001-09-18 02:26:39 +00001176
R David Murray19aeb432013-03-30 17:19:38 -04001177 def __init__(self, interval, function, args=None, kwargs=None):
Martin v. Löwis44f86962001-09-05 13:44:54 +00001178 Thread.__init__(self)
1179 self.interval = interval
1180 self.function = function
R David Murray19aeb432013-03-30 17:19:38 -04001181 self.args = args if args is not None else []
1182 self.kwargs = kwargs if kwargs is not None else {}
Martin v. Löwis44f86962001-09-05 13:44:54 +00001183 self.finished = Event()
Tim Petersb64bec32001-09-18 02:26:39 +00001184
Martin v. Löwis44f86962001-09-05 13:44:54 +00001185 def cancel(self):
Georg Brandlc30b59f2013-10-13 10:43:59 +02001186 """Stop the timer if it hasn't finished yet."""
Martin v. Löwis44f86962001-09-05 13:44:54 +00001187 self.finished.set()
Tim Petersb64bec32001-09-18 02:26:39 +00001188
Martin v. Löwis44f86962001-09-05 13:44:54 +00001189 def run(self):
1190 self.finished.wait(self.interval)
Benjamin Peterson672b8032008-06-11 19:14:14 +00001191 if not self.finished.is_set():
Martin v. Löwis44f86962001-09-05 13:44:54 +00001192 self.function(*self.args, **self.kwargs)
1193 self.finished.set()
Guido van Rossum7f5013a1998-04-09 22:01:42 +00001194
1195# Special thread class to represent the main thread
1196# This is garbage collected through an exit handler
1197
1198class _MainThread(Thread):
1199
1200 def __init__(self):
Antoine Pitrou0bd4deb2011-02-25 22:07:43 +00001201 Thread.__init__(self, name="MainThread", daemon=False)
Tim Petersc363a232013-09-08 18:44:40 -05001202 self._set_tstate_lock()
Christian Heimes9e7f1d22008-02-28 12:27:11 +00001203 self._started.set()
Benjamin Petersond23f8222009-04-05 19:13:16 +00001204 self._set_ident()
1205 with _active_limbo_lock:
1206 _active[self._ident] = self
Guido van Rossum7f5013a1998-04-09 22:01:42 +00001207
Guido van Rossum7f5013a1998-04-09 22:01:42 +00001208
1209# Dummy thread class to represent threads not started here.
Tim Peters711906e2005-01-08 07:30:42 +00001210# These aren't garbage collected when they die, nor can they be waited for.
Benjamin Peterson672b8032008-06-11 19:14:14 +00001211# If they invoke anything in threading.py that calls current_thread(), they
Tim Peters711906e2005-01-08 07:30:42 +00001212# leave an entry in the _active dict forever after.
Benjamin Peterson672b8032008-06-11 19:14:14 +00001213# Their purpose is to return *something* from current_thread().
Guido van Rossum7f5013a1998-04-09 22:01:42 +00001214# They are marked as daemon threads so we won't wait for them
1215# when we exit (conform previous semantics).
1216
1217class _DummyThread(Thread):
Tim Petersb90f89a2001-01-15 03:26:36 +00001218
Guido van Rossum7f5013a1998-04-09 22:01:42 +00001219 def __init__(self):
Antoine Pitrou0bd4deb2011-02-25 22:07:43 +00001220 Thread.__init__(self, name=_newname("Dummy-%d"), daemon=True)
Tim Peters711906e2005-01-08 07:30:42 +00001221
Christian Heimes9e7f1d22008-02-28 12:27:11 +00001222 self._started.set()
Benjamin Petersond23f8222009-04-05 19:13:16 +00001223 self._set_ident()
1224 with _active_limbo_lock:
1225 _active[self._ident] = self
Guido van Rossum7f5013a1998-04-09 22:01:42 +00001226
Antoine Pitrou8e6e0fd2012-04-19 23:55:01 +02001227 def _stop(self):
1228 pass
1229
Neal Norwitz45bec8c2002-02-19 03:01:36 +00001230 def join(self, timeout=None):
Guido van Rossum8ca162f2002-04-07 06:36:23 +00001231 assert False, "cannot join a dummy thread"
Guido van Rossum7f5013a1998-04-09 22:01:42 +00001232
1233
1234# Global API functions
1235
Benjamin Peterson672b8032008-06-11 19:14:14 +00001236def current_thread():
Georg Brandlc30b59f2013-10-13 10:43:59 +02001237 """Return the current Thread object, corresponding to the caller's thread of control.
1238
1239 If the caller's thread of control was not created through the threading
1240 module, a dummy thread object with limited functionality is returned.
1241
1242 """
Guido van Rossum7f5013a1998-04-09 22:01:42 +00001243 try:
Victor Stinner2a129742011-05-30 23:02:52 +02001244 return _active[get_ident()]
Guido van Rossum7f5013a1998-04-09 22:01:42 +00001245 except KeyError:
Guido van Rossum7f5013a1998-04-09 22:01:42 +00001246 return _DummyThread()
1247
Benjamin Petersonb3085c92008-09-01 23:09:31 +00001248currentThread = current_thread
Benjamin Petersonf0923f52008-08-18 22:10:13 +00001249
Benjamin Peterson672b8032008-06-11 19:14:14 +00001250def active_count():
Georg Brandlc30b59f2013-10-13 10:43:59 +02001251 """Return the number of Thread objects currently alive.
1252
1253 The returned count is equal to the length of the list returned by
1254 enumerate().
1255
1256 """
Benjamin Petersond23f8222009-04-05 19:13:16 +00001257 with _active_limbo_lock:
1258 return len(_active) + len(_limbo)
Guido van Rossum7f5013a1998-04-09 22:01:42 +00001259
Benjamin Petersonb3085c92008-09-01 23:09:31 +00001260activeCount = active_count
Benjamin Petersonf0923f52008-08-18 22:10:13 +00001261
Antoine Pitroubdec11f2009-11-05 13:49:14 +00001262def _enumerate():
1263 # Same as enumerate(), but without the lock. Internal use only.
1264 return list(_active.values()) + list(_limbo.values())
1265
Guido van Rossum7f5013a1998-04-09 22:01:42 +00001266def enumerate():
Georg Brandlc30b59f2013-10-13 10:43:59 +02001267 """Return a list of all Thread objects currently alive.
1268
1269 The list includes daemonic threads, dummy thread objects created by
1270 current_thread(), and the main thread. It excludes terminated threads and
1271 threads that have not yet been started.
1272
1273 """
Benjamin Petersond23f8222009-04-05 19:13:16 +00001274 with _active_limbo_lock:
1275 return list(_active.values()) + list(_limbo.values())
Guido van Rossum7f5013a1998-04-09 22:01:42 +00001276
Georg Brandl2067bfd2008-05-25 13:05:15 +00001277from _thread import stack_size
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001278
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001279# Create the main thread object,
1280# and make it available for the interpreter
1281# (Py_Main) as threading._shutdown.
Guido van Rossum7f5013a1998-04-09 22:01:42 +00001282
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +03001283_main_thread = _MainThread()
1284
1285def _shutdown():
Tim Petersc363a232013-09-08 18:44:40 -05001286 # Obscure: other threads may be waiting to join _main_thread. That's
1287 # dubious, but some code does it. We can't wait for C code to release
1288 # the main thread's tstate_lock - that won't happen until the interpreter
1289 # is nearly dead. So we release it here. Note that just calling _stop()
1290 # isn't enough: other threads may already be waiting on _tstate_lock.
Tim Petersb5e9ac92013-09-09 14:41:50 -05001291 tlock = _main_thread._tstate_lock
1292 # The main thread isn't finished yet, so its thread state lock can't have
1293 # been released.
1294 assert tlock is not None
1295 assert tlock.locked()
1296 tlock.release()
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +03001297 _main_thread._stop()
1298 t = _pickSomeNonDaemonThread()
1299 while t:
1300 t.join()
1301 t = _pickSomeNonDaemonThread()
1302 _main_thread._delete()
1303
1304def _pickSomeNonDaemonThread():
1305 for t in enumerate():
1306 if not t.daemon and t.is_alive():
1307 return t
1308 return None
1309
1310def main_thread():
Andrew Svetlovb1dd5572013-09-04 10:33:11 +03001311 """Return the main thread object.
1312
1313 In normal conditions, the main thread is the thread from which the
1314 Python interpreter was started.
1315 """
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +03001316 return _main_thread
Guido van Rossum7f5013a1998-04-09 22:01:42 +00001317
Jim Fultond15dc062004-07-14 19:11:50 +00001318# get thread-local implementation, either from the thread
1319# module, or from the python fallback
1320
1321try:
Georg Brandl2067bfd2008-05-25 13:05:15 +00001322 from _thread import _local as local
Brett Cannoncd171c82013-07-04 17:43:24 -04001323except ImportError:
Jim Fultond15dc062004-07-14 19:11:50 +00001324 from _threading_local import local
1325
Guido van Rossum7f5013a1998-04-09 22:01:42 +00001326
Jesse Nollera8513972008-07-17 16:49:17 +00001327def _after_fork():
1328 # This function is called by Python/ceval.c:PyEval_ReInitThreads which
1329 # is called from PyOS_AfterFork. Here we cleanup threading module state
1330 # that should not exist after a fork.
1331
1332 # Reset _active_limbo_lock, in case we forked while the lock was held
1333 # by another (non-forked) thread. http://bugs.python.org/issue874900
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +03001334 global _active_limbo_lock, _main_thread
Jesse Nollera8513972008-07-17 16:49:17 +00001335 _active_limbo_lock = _allocate_lock()
1336
1337 # fork() only copied the current thread; clear references to others.
1338 new_active = {}
1339 current = current_thread()
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +03001340 _main_thread = current
Jesse Nollera8513972008-07-17 16:49:17 +00001341 with _active_limbo_lock:
Antoine Pitrou5da7e792013-09-08 13:19:06 +02001342 # Dangling thread instances must still have their locks reset,
1343 # because someone may join() them.
1344 threads = set(_enumerate())
1345 threads.update(_dangling)
1346 for thread in threads:
Charles-François Natalib055bf62011-12-18 18:45:16 +01001347 # Any lock/condition variable may be currently locked or in an
1348 # invalid state, so we reinitialize them.
Jesse Nollera8513972008-07-17 16:49:17 +00001349 if thread is current:
Antoine Pitrou5fe291f2008-09-06 23:00:03 +00001350 # There is only one active thread. We reset the ident to
1351 # its new value since it can have changed.
Antoine Pitrou7b476992013-09-07 23:38:37 +02001352 thread._reset_internal_locks(True)
Victor Stinner2a129742011-05-30 23:02:52 +02001353 ident = get_ident()
Antoine Pitrou5fe291f2008-09-06 23:00:03 +00001354 thread._ident = ident
Jesse Nollera8513972008-07-17 16:49:17 +00001355 new_active[ident] = thread
1356 else:
1357 # All the others are already stopped.
Antoine Pitrou7b476992013-09-07 23:38:37 +02001358 thread._reset_internal_locks(False)
Charles-François Natalib055bf62011-12-18 18:45:16 +01001359 thread._stop()
Jesse Nollera8513972008-07-17 16:49:17 +00001360
1361 _limbo.clear()
1362 _active.clear()
1363 _active.update(new_active)
1364 assert len(_active) == 1