blob: 4f6ec4b18695135eba60e5ed807686f23ada0219 [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
4
5try:
6 import thread
7except ImportError:
8 del _sys.modules[__name__]
9 raise
10
Jeffrey Yasskin105f3d42008-03-31 00:35:53 +000011import warnings
Benjamin Petersonf4395602008-06-11 17:50:00 +000012
13from functools import wraps
Fred Drakea8725952002-12-30 23:32:50 +000014from time import time as _time, sleep as _sleep
Neil Schemenauerf607fc52003-11-05 23:03:00 +000015from traceback import format_exc as _format_exc
Raymond Hettinger756b3f32004-01-29 06:37:52 +000016from collections import deque
Guido van Rossum7f5013a1998-04-09 22:01:42 +000017
Benjamin Peterson973e6c22008-09-01 23:12:58 +000018# Note regarding PEP 8 compliant aliases
19# This threading model was originally inspired by Java, and inherited
20# the convention of camelCase function and method names from that
21# language. While those names are not in any imminent danger of being
22# deprecated, starting with Python 2.6, the module now provides a
23# PEP 8 compliant alias for any such method name.
24# Using the new PEP 8 compliant names also facilitates substitution
25# with the multiprocessing module, which doesn't provide the old
26# Java inspired names.
27
28
Guido van Rossum7f5013a1998-04-09 22:01:42 +000029# Rename some stuff so "from threading import *" is safe
Benjamin Peterson13f73822008-06-11 18:02:31 +000030__all__ = ['activeCount', 'active_count', 'Condition', 'currentThread',
31 'current_thread', 'enumerate', 'Event',
Tim Peters685e6972003-06-29 16:50:06 +000032 'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Thread',
Andrew MacIntyre92913322006-06-13 15:04:24 +000033 'Timer', 'setprofile', 'settrace', 'local', 'stack_size']
Guido van Rossum7f5013a1998-04-09 22:01:42 +000034
Guido van Rossum7f5013a1998-04-09 22:01:42 +000035_start_new_thread = thread.start_new_thread
36_allocate_lock = thread.allocate_lock
37_get_ident = thread.get_ident
Jeremy Hyltonb5fc7492000-06-01 01:17:17 +000038ThreadError = thread.error
Guido van Rossum7f5013a1998-04-09 22:01:42 +000039del thread
40
Guido van Rossum7f5013a1998-04-09 22:01:42 +000041
Jeffrey Yasskin105f3d42008-03-31 00:35:53 +000042# sys.exc_clear is used to work around the fact that except blocks
43# don't fully clear the exception until 3.0.
44warnings.filterwarnings('ignore', category=DeprecationWarning,
45 module='threading', message='sys.exc_clear')
46
Tim Peters59aba122003-07-01 20:01:55 +000047# Debug support (adapted from ihooks.py).
48# All the major classes here derive from _Verbose. We force that to
49# be a new-style class so that all the major classes here are new-style.
50# This helps debugging (type(instance) is more revealing for instances
51# of new-style classes).
Guido van Rossum7f5013a1998-04-09 22:01:42 +000052
Tim Peters0939fac2003-07-01 19:28:44 +000053_VERBOSE = False
Guido van Rossum7f5013a1998-04-09 22:01:42 +000054
55if __debug__:
56
Tim Peters59aba122003-07-01 20:01:55 +000057 class _Verbose(object):
Guido van Rossum7f5013a1998-04-09 22:01:42 +000058
59 def __init__(self, verbose=None):
60 if verbose is None:
61 verbose = _VERBOSE
62 self.__verbose = verbose
63
64 def _note(self, format, *args):
65 if self.__verbose:
66 format = format % args
67 format = "%s: %s\n" % (
Benjamin Petersonb6a95562008-08-22 20:43:48 +000068 current_thread().name, format)
Guido van Rossum7f5013a1998-04-09 22:01:42 +000069 _sys.stderr.write(format)
70
71else:
72 # Disable this when using "python -O"
Tim Peters59aba122003-07-01 20:01:55 +000073 class _Verbose(object):
Guido van Rossum7f5013a1998-04-09 22:01:42 +000074 def __init__(self, verbose=None):
75 pass
76 def _note(self, *args):
77 pass
78
Jeremy Hyltonbfccb352003-06-29 16:58:41 +000079# Support for profile and trace hooks
80
81_profile_hook = None
82_trace_hook = None
83
84def setprofile(func):
85 global _profile_hook
86 _profile_hook = func
Tim Petersd1b108b2003-06-29 17:24:17 +000087
Jeremy Hyltonbfccb352003-06-29 16:58:41 +000088def settrace(func):
89 global _trace_hook
90 _trace_hook = func
Guido van Rossum7f5013a1998-04-09 22:01:42 +000091
92# Synchronization classes
93
94Lock = _allocate_lock
95
96def RLock(*args, **kwargs):
Guido van Rossum68468eb2003-02-27 20:14:51 +000097 return _RLock(*args, **kwargs)
Guido van Rossum7f5013a1998-04-09 22:01:42 +000098
99class _RLock(_Verbose):
Tim Petersb90f89a2001-01-15 03:26:36 +0000100
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000101 def __init__(self, verbose=None):
102 _Verbose.__init__(self, verbose)
103 self.__block = _allocate_lock()
104 self.__owner = None
105 self.__count = 0
106
107 def __repr__(self):
Nick Coghlanf8bbaa92007-07-31 13:38:01 +0000108 owner = self.__owner
Antoine Pitroud7158d42009-11-09 16:00:11 +0000109 try:
110 owner = _active[owner].name
111 except KeyError:
112 pass
113 return "<%s owner=%r count=%d>" % (
114 self.__class__.__name__, owner, self.__count)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000115
116 def acquire(self, blocking=1):
Antoine Pitroud7158d42009-11-09 16:00:11 +0000117 me = _get_ident()
118 if self.__owner == me:
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000119 self.__count = self.__count + 1
120 if __debug__:
121 self._note("%s.acquire(%s): recursive success", self, blocking)
122 return 1
123 rc = self.__block.acquire(blocking)
124 if rc:
125 self.__owner = me
126 self.__count = 1
127 if __debug__:
Brett Cannon90cece72005-01-27 22:48:30 +0000128 self._note("%s.acquire(%s): initial success", self, blocking)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000129 else:
130 if __debug__:
131 self._note("%s.acquire(%s): failure", self, blocking)
132 return rc
133
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000134 __enter__ = acquire
135
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000136 def release(self):
Antoine Pitroud7158d42009-11-09 16:00:11 +0000137 if self.__owner != _get_ident():
Georg Brandle1254d72009-10-14 15:51:48 +0000138 raise RuntimeError("cannot release un-acquired lock")
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000139 self.__count = count = self.__count - 1
140 if not count:
141 self.__owner = None
142 self.__block.release()
143 if __debug__:
144 self._note("%s.release(): final release", self)
145 else:
146 if __debug__:
147 self._note("%s.release(): non-final release", self)
148
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000149 def __exit__(self, t, v, tb):
150 self.release()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000151
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000152 # Internal methods used by condition variables
153
Brett Cannon20050502008-08-02 03:13:46 +0000154 def _acquire_restore(self, count_owner):
155 count, owner = count_owner
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000156 self.__block.acquire()
157 self.__count = count
158 self.__owner = owner
159 if __debug__:
160 self._note("%s._acquire_restore()", self)
161
162 def _release_save(self):
163 if __debug__:
164 self._note("%s._release_save()", self)
165 count = self.__count
166 self.__count = 0
167 owner = self.__owner
168 self.__owner = None
169 self.__block.release()
170 return (count, owner)
171
172 def _is_owned(self):
Antoine Pitroud7158d42009-11-09 16:00:11 +0000173 return self.__owner == _get_ident()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000174
175
176def Condition(*args, **kwargs):
Guido van Rossum68468eb2003-02-27 20:14:51 +0000177 return _Condition(*args, **kwargs)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000178
179class _Condition(_Verbose):
180
181 def __init__(self, lock=None, verbose=None):
182 _Verbose.__init__(self, verbose)
183 if lock is None:
184 lock = RLock()
185 self.__lock = lock
186 # Export the lock's acquire() and release() methods
187 self.acquire = lock.acquire
188 self.release = lock.release
189 # If the lock defines _release_save() and/or _acquire_restore(),
190 # these override the default implementations (which just call
191 # release() and acquire() on the lock). Ditto for _is_owned().
192 try:
193 self._release_save = lock._release_save
194 except AttributeError:
195 pass
196 try:
197 self._acquire_restore = lock._acquire_restore
198 except AttributeError:
199 pass
200 try:
201 self._is_owned = lock._is_owned
202 except AttributeError:
203 pass
204 self.__waiters = []
205
Guido van Rossumda5b7012006-05-02 19:47:52 +0000206 def __enter__(self):
207 return self.__lock.__enter__()
208
209 def __exit__(self, *args):
210 return self.__lock.__exit__(*args)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000211
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000212 def __repr__(self):
213 return "<Condition(%s, %d)>" % (self.__lock, len(self.__waiters))
214
215 def _release_save(self):
216 self.__lock.release() # No state to save
217
218 def _acquire_restore(self, x):
219 self.__lock.acquire() # Ignore saved state
220
221 def _is_owned(self):
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000222 # Return True if lock is owned by current_thread.
Jeremy Hyltonaf7fde72002-08-14 17:43:59 +0000223 # This method is called only if __lock doesn't have _is_owned().
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000224 if self.__lock.acquire(0):
225 self.__lock.release()
Tim Petersbc0e9102002-04-04 22:55:58 +0000226 return False
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000227 else:
Tim Petersbc0e9102002-04-04 22:55:58 +0000228 return True
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000229
230 def wait(self, timeout=None):
Collin Winter50b79ce2007-06-06 00:17:35 +0000231 if not self._is_owned():
Georg Brandle1254d72009-10-14 15:51:48 +0000232 raise RuntimeError("cannot wait on un-acquired lock")
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000233 waiter = _allocate_lock()
234 waiter.acquire()
235 self.__waiters.append(waiter)
236 saved_state = self._release_save()
Tim Petersc951bf92001-04-02 20:15:57 +0000237 try: # restore state no matter what (e.g., KeyboardInterrupt)
238 if timeout is None:
239 waiter.acquire()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000240 if __debug__:
Tim Petersc951bf92001-04-02 20:15:57 +0000241 self._note("%s.wait(): got it", self)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000242 else:
Tim Petersa6a4f272001-08-12 00:41:33 +0000243 # Balancing act: We can't afford a pure busy loop, so we
244 # have to sleep; but if we sleep the whole timeout time,
245 # we'll be unresponsive. The scheme here sleeps very
246 # little at first, longer as time goes on, but never longer
247 # than 20 times per second (or the timeout time remaining).
Tim Petersc951bf92001-04-02 20:15:57 +0000248 endtime = _time() + timeout
Tim Petersa6a4f272001-08-12 00:41:33 +0000249 delay = 0.0005 # 500 us -> initial delay of 1 ms
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000250 while True:
Tim Petersc951bf92001-04-02 20:15:57 +0000251 gotit = waiter.acquire(0)
Tim Petersa6a4f272001-08-12 00:41:33 +0000252 if gotit:
Tim Petersc951bf92001-04-02 20:15:57 +0000253 break
Tim Petersa6a4f272001-08-12 00:41:33 +0000254 remaining = endtime - _time()
255 if remaining <= 0:
256 break
257 delay = min(delay * 2, remaining, .05)
Tim Petersc951bf92001-04-02 20:15:57 +0000258 _sleep(delay)
Tim Petersc951bf92001-04-02 20:15:57 +0000259 if not gotit:
260 if __debug__:
261 self._note("%s.wait(%s): timed out", self, timeout)
262 try:
263 self.__waiters.remove(waiter)
264 except ValueError:
265 pass
266 else:
267 if __debug__:
268 self._note("%s.wait(%s): got it", self, timeout)
269 finally:
270 self._acquire_restore(saved_state)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000271
272 def notify(self, n=1):
Collin Winter50b79ce2007-06-06 00:17:35 +0000273 if not self._is_owned():
Georg Brandle1254d72009-10-14 15:51:48 +0000274 raise RuntimeError("cannot notify on un-acquired lock")
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000275 __waiters = self.__waiters
276 waiters = __waiters[:n]
277 if not waiters:
278 if __debug__:
279 self._note("%s.notify(): no waiters", self)
280 return
281 self._note("%s.notify(): notifying %d waiter%s", self, n,
282 n!=1 and "s" or "")
283 for waiter in waiters:
284 waiter.release()
285 try:
286 __waiters.remove(waiter)
287 except ValueError:
288 pass
289
Benjamin Peterson973e6c22008-09-01 23:12:58 +0000290 def notifyAll(self):
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000291 self.notify(len(self.__waiters))
292
Benjamin Peterson973e6c22008-09-01 23:12:58 +0000293 notify_all = notifyAll
Benjamin Petersonf4395602008-06-11 17:50:00 +0000294
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000295
296def Semaphore(*args, **kwargs):
Guido van Rossum68468eb2003-02-27 20:14:51 +0000297 return _Semaphore(*args, **kwargs)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000298
299class _Semaphore(_Verbose):
300
Andrew M. Kuchling39d3bfc2000-02-29 00:10:24 +0000301 # After Tim Peters' semaphore class, but not quite the same (no maximum)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000302
303 def __init__(self, value=1, verbose=None):
Collin Winter50b79ce2007-06-06 00:17:35 +0000304 if value < 0:
305 raise ValueError("semaphore initial value must be >= 0")
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000306 _Verbose.__init__(self, verbose)
307 self.__cond = Condition(Lock())
308 self.__value = value
309
310 def acquire(self, blocking=1):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000311 rc = False
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000312 self.__cond.acquire()
313 while self.__value == 0:
314 if not blocking:
315 break
Skip Montanarob446fc72001-08-19 04:25:24 +0000316 if __debug__:
317 self._note("%s.acquire(%s): blocked waiting, value=%s",
318 self, blocking, self.__value)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000319 self.__cond.wait()
320 else:
321 self.__value = self.__value - 1
Skip Montanarob446fc72001-08-19 04:25:24 +0000322 if __debug__:
Skip Montanaroae8454a2001-08-19 05:53:47 +0000323 self._note("%s.acquire: success, value=%s",
324 self, self.__value)
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000325 rc = True
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000326 self.__cond.release()
327 return rc
328
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000329 __enter__ = acquire
330
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000331 def release(self):
332 self.__cond.acquire()
333 self.__value = self.__value + 1
Skip Montanarob446fc72001-08-19 04:25:24 +0000334 if __debug__:
Skip Montanaroae8454a2001-08-19 05:53:47 +0000335 self._note("%s.release: success, value=%s",
336 self, self.__value)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000337 self.__cond.notify()
338 self.__cond.release()
339
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000340 def __exit__(self, t, v, tb):
341 self.release()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000342
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000343
Skip Montanaroe428bb72001-08-20 20:27:58 +0000344def BoundedSemaphore(*args, **kwargs):
Guido van Rossum68468eb2003-02-27 20:14:51 +0000345 return _BoundedSemaphore(*args, **kwargs)
Skip Montanaroe428bb72001-08-20 20:27:58 +0000346
347class _BoundedSemaphore(_Semaphore):
348 """Semaphore that checks that # releases is <= # acquires"""
349 def __init__(self, value=1, verbose=None):
350 _Semaphore.__init__(self, value, verbose)
351 self._initial_value = value
352
353 def release(self):
354 if self._Semaphore__value >= self._initial_value:
355 raise ValueError, "Semaphore released too many times"
356 return _Semaphore.release(self)
357
358
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000359def Event(*args, **kwargs):
Guido van Rossum68468eb2003-02-27 20:14:51 +0000360 return _Event(*args, **kwargs)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000361
362class _Event(_Verbose):
363
364 # After Tim Peters' event class (without is_posted())
365
366 def __init__(self, verbose=None):
367 _Verbose.__init__(self, verbose)
368 self.__cond = Condition(Lock())
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000369 self.__flag = False
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000370
Benjamin Peterson973e6c22008-09-01 23:12:58 +0000371 def isSet(self):
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000372 return self.__flag
373
Benjamin Peterson973e6c22008-09-01 23:12:58 +0000374 is_set = isSet
Benjamin Petersonf4395602008-06-11 17:50:00 +0000375
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000376 def set(self):
Raymond Hettinger70ec29d2008-01-24 18:12:23 +0000377 self.__cond.acquire()
378 try:
Guido van Rossum21b60142002-11-21 21:08:39 +0000379 self.__flag = True
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000380 self.__cond.notify_all()
Raymond Hettinger70ec29d2008-01-24 18:12:23 +0000381 finally:
382 self.__cond.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000383
384 def clear(self):
Raymond Hettinger70ec29d2008-01-24 18:12:23 +0000385 self.__cond.acquire()
386 try:
Guido van Rossum21b60142002-11-21 21:08:39 +0000387 self.__flag = False
Raymond Hettinger70ec29d2008-01-24 18:12:23 +0000388 finally:
389 self.__cond.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000390
391 def wait(self, timeout=None):
Raymond Hettinger70ec29d2008-01-24 18:12:23 +0000392 self.__cond.acquire()
393 try:
Guido van Rossum21b60142002-11-21 21:08:39 +0000394 if not self.__flag:
395 self.__cond.wait(timeout)
Georg Brandlef660e82009-03-31 20:41:08 +0000396 return self.__flag
Raymond Hettinger70ec29d2008-01-24 18:12:23 +0000397 finally:
398 self.__cond.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000399
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000400# Helper to generate new thread names
401_counter = 0
402def _newname(template="Thread-%d"):
403 global _counter
404 _counter = _counter + 1
405 return template % _counter
406
407# Active thread administration
408_active_limbo_lock = _allocate_lock()
Tim Peters711906e2005-01-08 07:30:42 +0000409_active = {} # maps thread id to Thread object
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000410_limbo = {}
411
412
413# Main class for threads
414
415class Thread(_Verbose):
416
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000417 __initialized = False
Brett Cannoncc4e9352004-07-03 03:52:35 +0000418 # Need to store a reference to sys.exc_info for printing
419 # out exceptions when a thread tries to use a global var. during interp.
420 # shutdown and thus raises an exception about trying to perform some
421 # operation on/with a NoneType
422 __exc_info = _sys.exc_info
Jeffrey Yasskin8b9091f2008-03-28 04:11:18 +0000423 # Keep sys.exc_clear too to clear the exception just before
424 # allowing .join() to return.
425 __exc_clear = _sys.exc_clear
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000426
427 def __init__(self, group=None, target=None, name=None,
Georg Brandla4a8b822005-07-15 09:13:21 +0000428 args=(), kwargs=None, verbose=None):
Guido van Rossum5a43e1a1998-06-09 19:04:26 +0000429 assert group is None, "group argument must be None for now"
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000430 _Verbose.__init__(self, verbose)
Georg Brandla4a8b822005-07-15 09:13:21 +0000431 if kwargs is None:
432 kwargs = {}
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000433 self.__target = target
434 self.__name = str(name or _newname())
435 self.__args = args
436 self.__kwargs = kwargs
437 self.__daemonic = self._set_daemon()
Gregory P. Smith8856dda2008-06-01 23:48:47 +0000438 self.__ident = None
Jeffrey Yasskin69e13092008-02-28 06:09:19 +0000439 self.__started = Event()
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000440 self.__stopped = False
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000441 self.__block = Condition(Lock())
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000442 self.__initialized = True
Brett Cannoncc4e9352004-07-03 03:52:35 +0000443 # sys.stderr is not stored in the class like
444 # sys.exc_info since it can be changed between instances
445 self.__stderr = _sys.stderr
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000446
447 def _set_daemon(self):
448 # Overridden in _MainThread and _DummyThread
Benjamin Petersoncbae8692008-08-18 17:45:09 +0000449 return current_thread().daemon
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000450
451 def __repr__(self):
452 assert self.__initialized, "Thread.__init__() was not called"
453 status = "initial"
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000454 if self.__started.is_set():
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000455 status = "started"
456 if self.__stopped:
457 status = "stopped"
458 if self.__daemonic:
Gregory P. Smith8856dda2008-06-01 23:48:47 +0000459 status += " daemon"
460 if self.__ident is not None:
461 status += " %s" % self.__ident
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000462 return "<%s(%s, %s)>" % (self.__class__.__name__, self.__name, status)
463
464 def start(self):
Collin Winter50b79ce2007-06-06 00:17:35 +0000465 if not self.__initialized:
466 raise RuntimeError("thread.__init__() not called")
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000467 if self.__started.is_set():
Collin Winter50b79ce2007-06-06 00:17:35 +0000468 raise RuntimeError("thread already started")
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000469 if __debug__:
470 self._note("%s.start(): starting thread", self)
Benjamin Petersonbd9dd312009-03-31 21:06:30 +0000471 with _active_limbo_lock:
472 _limbo[self] = self
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000473 _start_new_thread(self.__bootstrap, ())
Jeffrey Yasskin69e13092008-02-28 06:09:19 +0000474 self.__started.wait()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000475
476 def run(self):
Jeffrey Yasskina885c152008-02-23 20:40:35 +0000477 try:
478 if self.__target:
479 self.__target(*self.__args, **self.__kwargs)
480 finally:
481 # Avoid a refcycle if the thread is running a function with
482 # an argument that has a member that points to the thread.
483 del self.__target, self.__args, self.__kwargs
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000484
485 def __bootstrap(self):
Guido van Rossum54ec61e2007-08-20 15:18:04 +0000486 # Wrapper around the real bootstrap code that ignores
487 # exceptions during interpreter cleanup. Those typically
488 # happen when a daemon thread wakes up at an unfortunate
489 # moment, finds the world around it destroyed, and raises some
490 # random exception *** while trying to report the exception in
491 # __bootstrap_inner() below ***. Those random exceptions
492 # don't help anybody, and they confuse users, so we suppress
493 # them. We suppress them only when it appears that the world
494 # indeed has already been destroyed, so that exceptions in
495 # __bootstrap_inner() during normal business hours are properly
496 # reported. Also, we only suppress them for daemonic threads;
497 # if a non-daemonic encounters this, something else is wrong.
498 try:
499 self.__bootstrap_inner()
500 except:
501 if self.__daemonic and _sys is None:
502 return
503 raise
504
Benjamin Petersond906ea62009-03-31 21:34:42 +0000505 def _set_ident(self):
506 self.__ident = _get_ident()
507
Guido van Rossum54ec61e2007-08-20 15:18:04 +0000508 def __bootstrap_inner(self):
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000509 try:
Benjamin Petersond906ea62009-03-31 21:34:42 +0000510 self._set_ident()
Jeffrey Yasskin69e13092008-02-28 06:09:19 +0000511 self.__started.set()
Benjamin Petersonbd9dd312009-03-31 21:06:30 +0000512 with _active_limbo_lock:
513 _active[self.__ident] = self
514 del _limbo[self]
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000515 if __debug__:
516 self._note("%s.__bootstrap(): thread started", self)
Jeremy Hyltonbfccb352003-06-29 16:58:41 +0000517
518 if _trace_hook:
519 self._note("%s.__bootstrap(): registering trace hook", self)
520 _sys.settrace(_trace_hook)
521 if _profile_hook:
522 self._note("%s.__bootstrap(): registering profile hook", self)
523 _sys.setprofile(_profile_hook)
Tim Petersd1b108b2003-06-29 17:24:17 +0000524
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000525 try:
526 self.run()
527 except SystemExit:
528 if __debug__:
529 self._note("%s.__bootstrap(): raised SystemExit", self)
530 except:
531 if __debug__:
532 self._note("%s.__bootstrap(): unhandled exception", self)
Brett Cannoncc4e9352004-07-03 03:52:35 +0000533 # If sys.stderr is no more (most likely from interpreter
534 # shutdown) use self.__stderr. Otherwise still use sys (as in
535 # _sys) in case sys.stderr was redefined since the creation of
536 # self.
537 if _sys:
538 _sys.stderr.write("Exception in thread %s:\n%s\n" %
Benjamin Petersonb6a95562008-08-22 20:43:48 +0000539 (self.name, _format_exc()))
Brett Cannoncc4e9352004-07-03 03:52:35 +0000540 else:
541 # Do the best job possible w/o a huge amt. of code to
542 # approximate a traceback (code ideas from
543 # Lib/traceback.py)
544 exc_type, exc_value, exc_tb = self.__exc_info()
545 try:
546 print>>self.__stderr, (
Benjamin Petersonb6a95562008-08-22 20:43:48 +0000547 "Exception in thread " + self.name +
Brett Cannoncc4e9352004-07-03 03:52:35 +0000548 " (most likely raised during interpreter shutdown):")
549 print>>self.__stderr, (
550 "Traceback (most recent call last):")
551 while exc_tb:
552 print>>self.__stderr, (
553 ' File "%s", line %s, in %s' %
554 (exc_tb.tb_frame.f_code.co_filename,
555 exc_tb.tb_lineno,
556 exc_tb.tb_frame.f_code.co_name))
557 exc_tb = exc_tb.tb_next
558 print>>self.__stderr, ("%s: %s" % (exc_type, exc_value))
559 # Make sure that exc_tb gets deleted since it is a memory
560 # hog; deleting everything else is just for thoroughness
561 finally:
562 del exc_type, exc_value, exc_tb
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000563 else:
564 if __debug__:
565 self._note("%s.__bootstrap(): normal return", self)
Jeffrey Yasskin8b9091f2008-03-28 04:11:18 +0000566 finally:
567 # Prevent a race in
568 # test_threading.test_no_refcycle_through_target when
569 # the exception keeps the target alive past when we
570 # assert that it's dead.
Amaury Forgeot d'Arc504a48f2008-03-29 01:41:08 +0000571 self.__exc_clear()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000572 finally:
Gregory P. Smith95cd5c02008-01-22 01:20:42 +0000573 with _active_limbo_lock:
574 self.__stop()
575 try:
576 # We don't call self.__delete() because it also
577 # grabs _active_limbo_lock.
578 del _active[_get_ident()]
579 except:
580 pass
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000581
582 def __stop(self):
Raymond Hettinger70ec29d2008-01-24 18:12:23 +0000583 self.__block.acquire()
584 self.__stopped = True
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000585 self.__block.notify_all()
Raymond Hettinger70ec29d2008-01-24 18:12:23 +0000586 self.__block.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000587
588 def __delete(self):
Tim Peters21429932004-07-21 03:36:52 +0000589 "Remove current thread from the dict of currently running threads."
Brett Cannon8b3d92a2004-07-21 02:21:58 +0000590
Tim Peters21429932004-07-21 03:36:52 +0000591 # Notes about running with dummy_thread:
592 #
593 # Must take care to not raise an exception if dummy_thread is being
594 # used (and thus this module is being used as an instance of
595 # dummy_threading). dummy_thread.get_ident() always returns -1 since
596 # there is only one thread if dummy_thread is being used. Thus
597 # len(_active) is always <= 1 here, and any Thread instance created
598 # overwrites the (if any) thread currently registered in _active.
599 #
600 # An instance of _MainThread is always created by 'threading'. This
601 # gets overwritten the instant an instance of Thread is created; both
602 # threads return -1 from dummy_thread.get_ident() and thus have the
603 # same key in the dict. So when the _MainThread instance created by
604 # 'threading' tries to clean itself up when atexit calls this method
605 # it gets a KeyError if another Thread instance was created.
606 #
607 # This all means that KeyError from trying to delete something from
608 # _active if dummy_threading is being used is a red herring. But
609 # since it isn't if dummy_threading is *not* being used then don't
610 # hide the exception.
Brett Cannon8b3d92a2004-07-21 02:21:58 +0000611
Raymond Hettinger70ec29d2008-01-24 18:12:23 +0000612 try:
Amaury Forgeot d'Arcd7a26512008-04-03 23:07:55 +0000613 with _active_limbo_lock:
Brett Cannon8b3d92a2004-07-21 02:21:58 +0000614 del _active[_get_ident()]
Amaury Forgeot d'Arcd7a26512008-04-03 23:07:55 +0000615 # There must not be any python code between the previous line
616 # and after the lock is released. Otherwise a tracing function
617 # could try to acquire the lock again in the same thread, (in
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000618 # current_thread()), and would block.
Amaury Forgeot d'Arcd7a26512008-04-03 23:07:55 +0000619 except KeyError:
620 if 'dummy_threading' not in _sys.modules:
621 raise
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000622
623 def join(self, timeout=None):
Collin Winter50b79ce2007-06-06 00:17:35 +0000624 if not self.__initialized:
625 raise RuntimeError("Thread.__init__() not called")
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000626 if not self.__started.is_set():
Collin Winter50b79ce2007-06-06 00:17:35 +0000627 raise RuntimeError("cannot join thread before it is started")
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000628 if self is current_thread():
Collin Winter50b79ce2007-06-06 00:17:35 +0000629 raise RuntimeError("cannot join current thread")
630
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000631 if __debug__:
632 if not self.__stopped:
633 self._note("%s.join(): waiting until thread stops", self)
Raymond Hettinger70ec29d2008-01-24 18:12:23 +0000634 self.__block.acquire()
635 try:
Brett Cannonad07ff22005-11-23 02:15:50 +0000636 if timeout is None:
637 while not self.__stopped:
638 self.__block.wait()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000639 if __debug__:
640 self._note("%s.join(): thread stopped", self)
Brett Cannonad07ff22005-11-23 02:15:50 +0000641 else:
642 deadline = _time() + timeout
643 while not self.__stopped:
644 delay = deadline - _time()
645 if delay <= 0:
646 if __debug__:
647 self._note("%s.join(): timed out", self)
648 break
649 self.__block.wait(delay)
650 else:
651 if __debug__:
652 self._note("%s.join(): thread stopped", self)
Raymond Hettinger70ec29d2008-01-24 18:12:23 +0000653 finally:
654 self.__block.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000655
Benjamin Petersoncbae8692008-08-18 17:45:09 +0000656 @property
657 def name(self):
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000658 assert self.__initialized, "Thread.__init__() not called"
659 return self.__name
660
Benjamin Petersoncbae8692008-08-18 17:45:09 +0000661 @name.setter
662 def name(self, name):
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000663 assert self.__initialized, "Thread.__init__() not called"
664 self.__name = str(name)
665
Benjamin Petersond8a89722008-08-18 16:40:03 +0000666 @property
667 def ident(self):
Gregory P. Smith8856dda2008-06-01 23:48:47 +0000668 assert self.__initialized, "Thread.__init__() not called"
669 return self.__ident
670
Benjamin Peterson973e6c22008-09-01 23:12:58 +0000671 def isAlive(self):
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000672 assert self.__initialized, "Thread.__init__() not called"
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000673 return self.__started.is_set() and not self.__stopped
Tim Petersb90f89a2001-01-15 03:26:36 +0000674
Benjamin Peterson973e6c22008-09-01 23:12:58 +0000675 is_alive = isAlive
Benjamin Peterson6ee1a312008-08-18 21:53:29 +0000676
Benjamin Petersoncbae8692008-08-18 17:45:09 +0000677 @property
678 def daemon(self):
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000679 assert self.__initialized, "Thread.__init__() not called"
680 return self.__daemonic
681
Benjamin Petersoncbae8692008-08-18 17:45:09 +0000682 @daemon.setter
683 def daemon(self, daemonic):
Collin Winter50b79ce2007-06-06 00:17:35 +0000684 if not self.__initialized:
685 raise RuntimeError("Thread.__init__() not called")
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000686 if self.__started.is_set():
Collin Winter50b79ce2007-06-06 00:17:35 +0000687 raise RuntimeError("cannot set daemon status of active thread");
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000688 self.__daemonic = daemonic
689
Benjamin Petersond8106262008-08-18 18:13:17 +0000690 def isDaemon(self):
691 return self.daemon
692
693 def setDaemon(self, daemonic):
694 self.daemon = daemonic
695
696 def getName(self):
697 return self.name
698
699 def setName(self, name):
700 self.name = name
701
Martin v. Löwis44f86962001-09-05 13:44:54 +0000702# The timer class was contributed by Itamar Shtull-Trauring
703
704def Timer(*args, **kwargs):
705 return _Timer(*args, **kwargs)
706
707class _Timer(Thread):
708 """Call a function after a specified number of seconds:
Tim Petersb64bec32001-09-18 02:26:39 +0000709
Martin v. Löwis44f86962001-09-05 13:44:54 +0000710 t = Timer(30.0, f, args=[], kwargs={})
711 t.start()
712 t.cancel() # stop the timer's action if it's still waiting
713 """
Tim Petersb64bec32001-09-18 02:26:39 +0000714
Martin v. Löwis44f86962001-09-05 13:44:54 +0000715 def __init__(self, interval, function, args=[], kwargs={}):
716 Thread.__init__(self)
717 self.interval = interval
718 self.function = function
719 self.args = args
720 self.kwargs = kwargs
721 self.finished = Event()
Tim Petersb64bec32001-09-18 02:26:39 +0000722
Martin v. Löwis44f86962001-09-05 13:44:54 +0000723 def cancel(self):
724 """Stop the timer if it hasn't finished yet"""
725 self.finished.set()
Tim Petersb64bec32001-09-18 02:26:39 +0000726
Martin v. Löwis44f86962001-09-05 13:44:54 +0000727 def run(self):
728 self.finished.wait(self.interval)
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000729 if not self.finished.is_set():
Martin v. Löwis44f86962001-09-05 13:44:54 +0000730 self.function(*self.args, **self.kwargs)
731 self.finished.set()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000732
733# Special thread class to represent the main thread
734# This is garbage collected through an exit handler
735
736class _MainThread(Thread):
737
738 def __init__(self):
739 Thread.__init__(self, name="MainThread")
Jeffrey Yasskin69e13092008-02-28 06:09:19 +0000740 self._Thread__started.set()
Benjamin Petersond906ea62009-03-31 21:34:42 +0000741 self._set_ident()
Benjamin Petersonbd9dd312009-03-31 21:06:30 +0000742 with _active_limbo_lock:
743 _active[_get_ident()] = self
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000744
745 def _set_daemon(self):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000746 return False
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000747
Martin v. Löwis7b7c9d42007-01-04 21:06:12 +0000748 def _exitfunc(self):
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000749 self._Thread__stop()
750 t = _pickSomeNonDaemonThread()
751 if t:
752 if __debug__:
753 self._note("%s: waiting for other threads", self)
754 while t:
755 t.join()
756 t = _pickSomeNonDaemonThread()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000757 if __debug__:
758 self._note("%s: exiting", self)
759 self._Thread__delete()
760
761def _pickSomeNonDaemonThread():
762 for t in enumerate():
Benjamin Petersoncbae8692008-08-18 17:45:09 +0000763 if not t.daemon and t.is_alive():
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000764 return t
765 return None
766
767
768# Dummy thread class to represent threads not started here.
Tim Peters711906e2005-01-08 07:30:42 +0000769# These aren't garbage collected when they die, nor can they be waited for.
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000770# If they invoke anything in threading.py that calls current_thread(), they
Tim Peters711906e2005-01-08 07:30:42 +0000771# leave an entry in the _active dict forever after.
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000772# Their purpose is to return *something* from current_thread().
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000773# They are marked as daemon threads so we won't wait for them
774# when we exit (conform previous semantics).
775
776class _DummyThread(Thread):
Tim Petersb90f89a2001-01-15 03:26:36 +0000777
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000778 def __init__(self):
779 Thread.__init__(self, name=_newname("Dummy-%d"))
Tim Peters711906e2005-01-08 07:30:42 +0000780
781 # Thread.__block consumes an OS-level locking primitive, which
782 # can never be used by a _DummyThread. Since a _DummyThread
783 # instance is immortal, that's bad, so release this resource.
Brett Cannone6539c42005-01-08 02:43:53 +0000784 del self._Thread__block
Tim Peters711906e2005-01-08 07:30:42 +0000785
Jeffrey Yasskin69e13092008-02-28 06:09:19 +0000786 self._Thread__started.set()
Benjamin Petersond906ea62009-03-31 21:34:42 +0000787 self._set_ident()
Benjamin Petersonbd9dd312009-03-31 21:06:30 +0000788 with _active_limbo_lock:
789 _active[_get_ident()] = self
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000790
791 def _set_daemon(self):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000792 return True
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000793
Neal Norwitz45bec8c2002-02-19 03:01:36 +0000794 def join(self, timeout=None):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000795 assert False, "cannot join a dummy thread"
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000796
797
798# Global API functions
799
Benjamin Peterson973e6c22008-09-01 23:12:58 +0000800def currentThread():
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000801 try:
802 return _active[_get_ident()]
803 except KeyError:
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000804 ##print "current_thread(): no current thread for", _get_ident()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000805 return _DummyThread()
806
Benjamin Peterson973e6c22008-09-01 23:12:58 +0000807current_thread = currentThread
Benjamin Petersonf4395602008-06-11 17:50:00 +0000808
Benjamin Peterson973e6c22008-09-01 23:12:58 +0000809def activeCount():
Benjamin Petersonbd9dd312009-03-31 21:06:30 +0000810 with _active_limbo_lock:
811 return len(_active) + len(_limbo)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000812
Benjamin Peterson973e6c22008-09-01 23:12:58 +0000813active_count = activeCount
Benjamin Petersonf4395602008-06-11 17:50:00 +0000814
Antoine Pitrou99c160b2009-11-05 13:42:29 +0000815def _enumerate():
816 # Same as enumerate(), but without the lock. Internal use only.
817 return _active.values() + _limbo.values()
818
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000819def enumerate():
Benjamin Petersonbd9dd312009-03-31 21:06:30 +0000820 with _active_limbo_lock:
821 return _active.values() + _limbo.values()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000822
Andrew MacIntyre92913322006-06-13 15:04:24 +0000823from thread import stack_size
824
Martin v. Löwis7b7c9d42007-01-04 21:06:12 +0000825# Create the main thread object,
826# and make it available for the interpreter
827# (Py_Main) as threading._shutdown.
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000828
Martin v. Löwis7b7c9d42007-01-04 21:06:12 +0000829_shutdown = _MainThread()._exitfunc
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000830
Jim Fultond15dc062004-07-14 19:11:50 +0000831# get thread-local implementation, either from the thread
832# module, or from the python fallback
833
834try:
835 from thread import _local as local
836except ImportError:
837 from _threading_local import local
838
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000839
Jesse Noller5e62ca42008-07-16 20:03:47 +0000840def _after_fork():
841 # This function is called by Python/ceval.c:PyEval_ReInitThreads which
842 # is called from PyOS_AfterFork. Here we cleanup threading module state
843 # that should not exist after a fork.
844
845 # Reset _active_limbo_lock, in case we forked while the lock was held
846 # by another (non-forked) thread. http://bugs.python.org/issue874900
847 global _active_limbo_lock
848 _active_limbo_lock = _allocate_lock()
849
850 # fork() only copied the current thread; clear references to others.
851 new_active = {}
852 current = current_thread()
853 with _active_limbo_lock:
Antoine Pitrou9fb1aca2008-09-06 23:04:32 +0000854 for thread in _active.itervalues():
Jesse Noller5e62ca42008-07-16 20:03:47 +0000855 if thread is current:
Antoine Pitrou9fb1aca2008-09-06 23:04:32 +0000856 # There is only one active thread. We reset the ident to
857 # its new value since it can have changed.
858 ident = _get_ident()
859 thread._Thread__ident = ident
Jesse Noller5e62ca42008-07-16 20:03:47 +0000860 new_active[ident] = thread
861 else:
862 # All the others are already stopped.
863 # We don't call _Thread__stop() because it tries to acquire
864 # thread._Thread__block which could also have been held while
865 # we forked.
866 thread._Thread__stopped = True
867
868 _limbo.clear()
869 _active.clear()
870 _active.update(new_active)
871 assert len(_active) == 1
872
873
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000874# Self-test code
875
876def _test():
877
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000878 class BoundedQueue(_Verbose):
879
880 def __init__(self, limit):
881 _Verbose.__init__(self)
882 self.mon = RLock()
883 self.rc = Condition(self.mon)
884 self.wc = Condition(self.mon)
885 self.limit = limit
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000886 self.queue = deque()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000887
888 def put(self, item):
889 self.mon.acquire()
890 while len(self.queue) >= self.limit:
891 self._note("put(%s): queue full", item)
892 self.wc.wait()
893 self.queue.append(item)
894 self._note("put(%s): appended, length now %d",
895 item, len(self.queue))
896 self.rc.notify()
897 self.mon.release()
898
899 def get(self):
900 self.mon.acquire()
901 while not self.queue:
902 self._note("get(): queue empty")
903 self.rc.wait()
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000904 item = self.queue.popleft()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000905 self._note("get(): got %s, %d left", item, len(self.queue))
906 self.wc.notify()
907 self.mon.release()
908 return item
909
910 class ProducerThread(Thread):
911
912 def __init__(self, queue, quota):
913 Thread.__init__(self, name="Producer")
914 self.queue = queue
915 self.quota = quota
916
917 def run(self):
Guido van Rossumb26a1b41998-05-20 17:05:52 +0000918 from random import random
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000919 counter = 0
920 while counter < self.quota:
921 counter = counter + 1
Benjamin Petersoncbae8692008-08-18 17:45:09 +0000922 self.queue.put("%s.%d" % (self.name, counter))
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000923 _sleep(random() * 0.00001)
924
925
926 class ConsumerThread(Thread):
927
928 def __init__(self, queue, count):
929 Thread.__init__(self, name="Consumer")
930 self.queue = queue
931 self.count = count
932
933 def run(self):
934 while self.count > 0:
935 item = self.queue.get()
936 print item
937 self.count = self.count - 1
938
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000939 NP = 3
940 QL = 4
941 NI = 5
942
943 Q = BoundedQueue(QL)
944 P = []
945 for i in range(NP):
946 t = ProducerThread(Q, NI)
Benjamin Petersoncbae8692008-08-18 17:45:09 +0000947 t.name = ("Producer-%d" % (i+1))
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000948 P.append(t)
949 C = ConsumerThread(Q, NI*NP)
950 for t in P:
951 t.start()
952 _sleep(0.000001)
953 C.start()
954 for t in P:
955 t.join()
956 C.join()
957
958if __name__ == '__main__':
959 _test()