blob: 56740101edb8ae5cde5a6c86129f0d73d5d63fa0 [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
Fred Drakea8725952002-12-30 23:32:50 +000013from time import time as _time, sleep as _sleep
Neil Schemenauerf607fc52003-11-05 23:03:00 +000014from traceback import format_exc as _format_exc
Raymond Hettinger756b3f32004-01-29 06:37:52 +000015from collections import deque
Guido van Rossum7f5013a1998-04-09 22:01:42 +000016
Benjamin Peterson973e6c22008-09-01 23:12:58 +000017# Note regarding PEP 8 compliant aliases
18# This threading model was originally inspired by Java, and inherited
19# the convention of camelCase function and method names from that
20# language. While those names are not in any imminent danger of being
21# deprecated, starting with Python 2.6, the module now provides a
22# PEP 8 compliant alias for any such method name.
23# Using the new PEP 8 compliant names also facilitates substitution
24# with the multiprocessing module, which doesn't provide the old
25# Java inspired names.
26
27
Guido van Rossum7f5013a1998-04-09 22:01:42 +000028# Rename some stuff so "from threading import *" is safe
Benjamin Peterson13f73822008-06-11 18:02:31 +000029__all__ = ['activeCount', 'active_count', 'Condition', 'currentThread',
30 'current_thread', 'enumerate', 'Event',
Tim Peters685e6972003-06-29 16:50:06 +000031 'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Thread',
Andrew MacIntyre92913322006-06-13 15:04:24 +000032 'Timer', 'setprofile', 'settrace', 'local', 'stack_size']
Guido van Rossum7f5013a1998-04-09 22:01:42 +000033
Guido van Rossum7f5013a1998-04-09 22:01:42 +000034_start_new_thread = thread.start_new_thread
35_allocate_lock = thread.allocate_lock
36_get_ident = thread.get_ident
Jeremy Hyltonb5fc7492000-06-01 01:17:17 +000037ThreadError = thread.error
Guido van Rossum7f5013a1998-04-09 22:01:42 +000038del thread
39
Guido van Rossum7f5013a1998-04-09 22:01:42 +000040
Jeffrey Yasskin105f3d42008-03-31 00:35:53 +000041# sys.exc_clear is used to work around the fact that except blocks
42# don't fully clear the exception until 3.0.
43warnings.filterwarnings('ignore', category=DeprecationWarning,
44 module='threading', message='sys.exc_clear')
45
Tim Peters59aba122003-07-01 20:01:55 +000046# Debug support (adapted from ihooks.py).
47# All the major classes here derive from _Verbose. We force that to
48# be a new-style class so that all the major classes here are new-style.
49# This helps debugging (type(instance) is more revealing for instances
50# of new-style classes).
Guido van Rossum7f5013a1998-04-09 22:01:42 +000051
Tim Peters0939fac2003-07-01 19:28:44 +000052_VERBOSE = False
Guido van Rossum7f5013a1998-04-09 22:01:42 +000053
54if __debug__:
55
Tim Peters59aba122003-07-01 20:01:55 +000056 class _Verbose(object):
Guido van Rossum7f5013a1998-04-09 22:01:42 +000057
58 def __init__(self, verbose=None):
59 if verbose is None:
60 verbose = _VERBOSE
61 self.__verbose = verbose
62
63 def _note(self, format, *args):
64 if self.__verbose:
65 format = format % args
66 format = "%s: %s\n" % (
Benjamin Petersonb6a95562008-08-22 20:43:48 +000067 current_thread().name, format)
Guido van Rossum7f5013a1998-04-09 22:01:42 +000068 _sys.stderr.write(format)
69
70else:
71 # Disable this when using "python -O"
Tim Peters59aba122003-07-01 20:01:55 +000072 class _Verbose(object):
Guido van Rossum7f5013a1998-04-09 22:01:42 +000073 def __init__(self, verbose=None):
74 pass
75 def _note(self, *args):
76 pass
77
Jeremy Hyltonbfccb352003-06-29 16:58:41 +000078# Support for profile and trace hooks
79
80_profile_hook = None
81_trace_hook = None
82
83def setprofile(func):
84 global _profile_hook
85 _profile_hook = func
Tim Petersd1b108b2003-06-29 17:24:17 +000086
Jeremy Hyltonbfccb352003-06-29 16:58:41 +000087def settrace(func):
88 global _trace_hook
89 _trace_hook = func
Guido van Rossum7f5013a1998-04-09 22:01:42 +000090
91# Synchronization classes
92
93Lock = _allocate_lock
94
95def RLock(*args, **kwargs):
Guido van Rossum68468eb2003-02-27 20:14:51 +000096 return _RLock(*args, **kwargs)
Guido van Rossum7f5013a1998-04-09 22:01:42 +000097
98class _RLock(_Verbose):
Tim Petersb90f89a2001-01-15 03:26:36 +000099
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000100 def __init__(self, verbose=None):
101 _Verbose.__init__(self, verbose)
102 self.__block = _allocate_lock()
103 self.__owner = None
104 self.__count = 0
105
106 def __repr__(self):
Nick Coghlanf8bbaa92007-07-31 13:38:01 +0000107 owner = self.__owner
Antoine Pitroud7158d42009-11-09 16:00:11 +0000108 try:
109 owner = _active[owner].name
110 except KeyError:
111 pass
112 return "<%s owner=%r count=%d>" % (
113 self.__class__.__name__, owner, self.__count)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000114
115 def acquire(self, blocking=1):
Antoine Pitroud7158d42009-11-09 16:00:11 +0000116 me = _get_ident()
117 if self.__owner == me:
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000118 self.__count = self.__count + 1
119 if __debug__:
120 self._note("%s.acquire(%s): recursive success", self, blocking)
121 return 1
122 rc = self.__block.acquire(blocking)
123 if rc:
124 self.__owner = me
125 self.__count = 1
126 if __debug__:
Brett Cannon90cece72005-01-27 22:48:30 +0000127 self._note("%s.acquire(%s): initial success", self, blocking)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000128 else:
129 if __debug__:
130 self._note("%s.acquire(%s): failure", self, blocking)
131 return rc
132
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000133 __enter__ = acquire
134
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000135 def release(self):
Antoine Pitroud7158d42009-11-09 16:00:11 +0000136 if self.__owner != _get_ident():
Georg Brandle1254d72009-10-14 15:51:48 +0000137 raise RuntimeError("cannot release un-acquired lock")
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000138 self.__count = count = self.__count - 1
139 if not count:
140 self.__owner = None
141 self.__block.release()
142 if __debug__:
143 self._note("%s.release(): final release", self)
144 else:
145 if __debug__:
146 self._note("%s.release(): non-final release", self)
147
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000148 def __exit__(self, t, v, tb):
149 self.release()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000150
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000151 # Internal methods used by condition variables
152
Brett Cannon20050502008-08-02 03:13:46 +0000153 def _acquire_restore(self, count_owner):
154 count, owner = count_owner
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000155 self.__block.acquire()
156 self.__count = count
157 self.__owner = owner
158 if __debug__:
159 self._note("%s._acquire_restore()", self)
160
161 def _release_save(self):
162 if __debug__:
163 self._note("%s._release_save()", self)
164 count = self.__count
165 self.__count = 0
166 owner = self.__owner
167 self.__owner = None
168 self.__block.release()
169 return (count, owner)
170
171 def _is_owned(self):
Antoine Pitroud7158d42009-11-09 16:00:11 +0000172 return self.__owner == _get_ident()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000173
174
175def Condition(*args, **kwargs):
Guido van Rossum68468eb2003-02-27 20:14:51 +0000176 return _Condition(*args, **kwargs)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000177
178class _Condition(_Verbose):
179
180 def __init__(self, lock=None, verbose=None):
181 _Verbose.__init__(self, verbose)
182 if lock is None:
183 lock = RLock()
184 self.__lock = lock
185 # Export the lock's acquire() and release() methods
186 self.acquire = lock.acquire
187 self.release = lock.release
188 # If the lock defines _release_save() and/or _acquire_restore(),
189 # these override the default implementations (which just call
190 # release() and acquire() on the lock). Ditto for _is_owned().
191 try:
192 self._release_save = lock._release_save
193 except AttributeError:
194 pass
195 try:
196 self._acquire_restore = lock._acquire_restore
197 except AttributeError:
198 pass
199 try:
200 self._is_owned = lock._is_owned
201 except AttributeError:
202 pass
203 self.__waiters = []
204
Guido van Rossumda5b7012006-05-02 19:47:52 +0000205 def __enter__(self):
206 return self.__lock.__enter__()
207
208 def __exit__(self, *args):
209 return self.__lock.__exit__(*args)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000210
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000211 def __repr__(self):
212 return "<Condition(%s, %d)>" % (self.__lock, len(self.__waiters))
213
214 def _release_save(self):
215 self.__lock.release() # No state to save
216
217 def _acquire_restore(self, x):
218 self.__lock.acquire() # Ignore saved state
219
220 def _is_owned(self):
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000221 # Return True if lock is owned by current_thread.
Jeremy Hyltonaf7fde72002-08-14 17:43:59 +0000222 # This method is called only if __lock doesn't have _is_owned().
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000223 if self.__lock.acquire(0):
224 self.__lock.release()
Tim Petersbc0e9102002-04-04 22:55:58 +0000225 return False
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000226 else:
Tim Petersbc0e9102002-04-04 22:55:58 +0000227 return True
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000228
229 def wait(self, timeout=None):
Collin Winter50b79ce2007-06-06 00:17:35 +0000230 if not self._is_owned():
Georg Brandle1254d72009-10-14 15:51:48 +0000231 raise RuntimeError("cannot wait on un-acquired lock")
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000232 waiter = _allocate_lock()
233 waiter.acquire()
234 self.__waiters.append(waiter)
235 saved_state = self._release_save()
Tim Petersc951bf92001-04-02 20:15:57 +0000236 try: # restore state no matter what (e.g., KeyboardInterrupt)
237 if timeout is None:
238 waiter.acquire()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000239 if __debug__:
Tim Petersc951bf92001-04-02 20:15:57 +0000240 self._note("%s.wait(): got it", self)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000241 else:
Tim Petersa6a4f272001-08-12 00:41:33 +0000242 # Balancing act: We can't afford a pure busy loop, so we
243 # have to sleep; but if we sleep the whole timeout time,
244 # we'll be unresponsive. The scheme here sleeps very
245 # little at first, longer as time goes on, but never longer
246 # than 20 times per second (or the timeout time remaining).
Tim Petersc951bf92001-04-02 20:15:57 +0000247 endtime = _time() + timeout
Tim Petersa6a4f272001-08-12 00:41:33 +0000248 delay = 0.0005 # 500 us -> initial delay of 1 ms
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000249 while True:
Tim Petersc951bf92001-04-02 20:15:57 +0000250 gotit = waiter.acquire(0)
Tim Petersa6a4f272001-08-12 00:41:33 +0000251 if gotit:
Tim Petersc951bf92001-04-02 20:15:57 +0000252 break
Tim Petersa6a4f272001-08-12 00:41:33 +0000253 remaining = endtime - _time()
254 if remaining <= 0:
255 break
256 delay = min(delay * 2, remaining, .05)
Tim Petersc951bf92001-04-02 20:15:57 +0000257 _sleep(delay)
Tim Petersc951bf92001-04-02 20:15:57 +0000258 if not gotit:
259 if __debug__:
260 self._note("%s.wait(%s): timed out", self, timeout)
261 try:
262 self.__waiters.remove(waiter)
263 except ValueError:
264 pass
265 else:
266 if __debug__:
267 self._note("%s.wait(%s): got it", self, timeout)
268 finally:
269 self._acquire_restore(saved_state)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000270
271 def notify(self, n=1):
Collin Winter50b79ce2007-06-06 00:17:35 +0000272 if not self._is_owned():
Georg Brandle1254d72009-10-14 15:51:48 +0000273 raise RuntimeError("cannot notify on un-acquired lock")
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000274 __waiters = self.__waiters
275 waiters = __waiters[:n]
276 if not waiters:
277 if __debug__:
278 self._note("%s.notify(): no waiters", self)
279 return
280 self._note("%s.notify(): notifying %d waiter%s", self, n,
281 n!=1 and "s" or "")
282 for waiter in waiters:
283 waiter.release()
284 try:
285 __waiters.remove(waiter)
286 except ValueError:
287 pass
288
Benjamin Peterson973e6c22008-09-01 23:12:58 +0000289 def notifyAll(self):
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000290 self.notify(len(self.__waiters))
291
Benjamin Peterson973e6c22008-09-01 23:12:58 +0000292 notify_all = notifyAll
Benjamin Petersonf4395602008-06-11 17:50:00 +0000293
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000294
295def Semaphore(*args, **kwargs):
Guido van Rossum68468eb2003-02-27 20:14:51 +0000296 return _Semaphore(*args, **kwargs)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000297
298class _Semaphore(_Verbose):
299
Andrew M. Kuchling39d3bfc2000-02-29 00:10:24 +0000300 # After Tim Peters' semaphore class, but not quite the same (no maximum)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000301
302 def __init__(self, value=1, verbose=None):
Collin Winter50b79ce2007-06-06 00:17:35 +0000303 if value < 0:
304 raise ValueError("semaphore initial value must be >= 0")
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000305 _Verbose.__init__(self, verbose)
306 self.__cond = Condition(Lock())
307 self.__value = value
308
309 def acquire(self, blocking=1):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000310 rc = False
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000311 self.__cond.acquire()
312 while self.__value == 0:
313 if not blocking:
314 break
Skip Montanarob446fc72001-08-19 04:25:24 +0000315 if __debug__:
316 self._note("%s.acquire(%s): blocked waiting, value=%s",
317 self, blocking, self.__value)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000318 self.__cond.wait()
319 else:
320 self.__value = self.__value - 1
Skip Montanarob446fc72001-08-19 04:25:24 +0000321 if __debug__:
Skip Montanaroae8454a2001-08-19 05:53:47 +0000322 self._note("%s.acquire: success, value=%s",
323 self, self.__value)
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000324 rc = True
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000325 self.__cond.release()
326 return rc
327
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000328 __enter__ = acquire
329
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000330 def release(self):
331 self.__cond.acquire()
332 self.__value = self.__value + 1
Skip Montanarob446fc72001-08-19 04:25:24 +0000333 if __debug__:
Skip Montanaroae8454a2001-08-19 05:53:47 +0000334 self._note("%s.release: success, value=%s",
335 self, self.__value)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000336 self.__cond.notify()
337 self.__cond.release()
338
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000339 def __exit__(self, t, v, tb):
340 self.release()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000341
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000342
Skip Montanaroe428bb72001-08-20 20:27:58 +0000343def BoundedSemaphore(*args, **kwargs):
Guido van Rossum68468eb2003-02-27 20:14:51 +0000344 return _BoundedSemaphore(*args, **kwargs)
Skip Montanaroe428bb72001-08-20 20:27:58 +0000345
346class _BoundedSemaphore(_Semaphore):
347 """Semaphore that checks that # releases is <= # acquires"""
348 def __init__(self, value=1, verbose=None):
349 _Semaphore.__init__(self, value, verbose)
350 self._initial_value = value
351
352 def release(self):
353 if self._Semaphore__value >= self._initial_value:
354 raise ValueError, "Semaphore released too many times"
355 return _Semaphore.release(self)
356
357
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000358def Event(*args, **kwargs):
Guido van Rossum68468eb2003-02-27 20:14:51 +0000359 return _Event(*args, **kwargs)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000360
361class _Event(_Verbose):
362
363 # After Tim Peters' event class (without is_posted())
364
365 def __init__(self, verbose=None):
366 _Verbose.__init__(self, verbose)
367 self.__cond = Condition(Lock())
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000368 self.__flag = False
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000369
Benjamin Peterson973e6c22008-09-01 23:12:58 +0000370 def isSet(self):
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000371 return self.__flag
372
Benjamin Peterson973e6c22008-09-01 23:12:58 +0000373 is_set = isSet
Benjamin Petersonf4395602008-06-11 17:50:00 +0000374
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000375 def set(self):
Raymond Hettinger70ec29d2008-01-24 18:12:23 +0000376 self.__cond.acquire()
377 try:
Guido van Rossum21b60142002-11-21 21:08:39 +0000378 self.__flag = True
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000379 self.__cond.notify_all()
Raymond Hettinger70ec29d2008-01-24 18:12:23 +0000380 finally:
381 self.__cond.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000382
383 def clear(self):
Raymond Hettinger70ec29d2008-01-24 18:12:23 +0000384 self.__cond.acquire()
385 try:
Guido van Rossum21b60142002-11-21 21:08:39 +0000386 self.__flag = False
Raymond Hettinger70ec29d2008-01-24 18:12:23 +0000387 finally:
388 self.__cond.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000389
390 def wait(self, timeout=None):
Raymond Hettinger70ec29d2008-01-24 18:12:23 +0000391 self.__cond.acquire()
392 try:
Guido van Rossum21b60142002-11-21 21:08:39 +0000393 if not self.__flag:
394 self.__cond.wait(timeout)
Georg Brandlef660e82009-03-31 20:41:08 +0000395 return self.__flag
Raymond Hettinger70ec29d2008-01-24 18:12:23 +0000396 finally:
397 self.__cond.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000398
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000399# Helper to generate new thread names
400_counter = 0
401def _newname(template="Thread-%d"):
402 global _counter
403 _counter = _counter + 1
404 return template % _counter
405
406# Active thread administration
407_active_limbo_lock = _allocate_lock()
Tim Peters711906e2005-01-08 07:30:42 +0000408_active = {} # maps thread id to Thread object
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000409_limbo = {}
410
411
412# Main class for threads
413
414class Thread(_Verbose):
415
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000416 __initialized = False
Brett Cannoncc4e9352004-07-03 03:52:35 +0000417 # Need to store a reference to sys.exc_info for printing
418 # out exceptions when a thread tries to use a global var. during interp.
419 # shutdown and thus raises an exception about trying to perform some
420 # operation on/with a NoneType
421 __exc_info = _sys.exc_info
Jeffrey Yasskin8b9091f2008-03-28 04:11:18 +0000422 # Keep sys.exc_clear too to clear the exception just before
423 # allowing .join() to return.
424 __exc_clear = _sys.exc_clear
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000425
426 def __init__(self, group=None, target=None, name=None,
Georg Brandla4a8b822005-07-15 09:13:21 +0000427 args=(), kwargs=None, verbose=None):
Guido van Rossum5a43e1a1998-06-09 19:04:26 +0000428 assert group is None, "group argument must be None for now"
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000429 _Verbose.__init__(self, verbose)
Georg Brandla4a8b822005-07-15 09:13:21 +0000430 if kwargs is None:
431 kwargs = {}
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000432 self.__target = target
433 self.__name = str(name or _newname())
434 self.__args = args
435 self.__kwargs = kwargs
436 self.__daemonic = self._set_daemon()
Gregory P. Smith8856dda2008-06-01 23:48:47 +0000437 self.__ident = None
Jeffrey Yasskin69e13092008-02-28 06:09:19 +0000438 self.__started = Event()
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000439 self.__stopped = False
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000440 self.__block = Condition(Lock())
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000441 self.__initialized = True
Brett Cannoncc4e9352004-07-03 03:52:35 +0000442 # sys.stderr is not stored in the class like
443 # sys.exc_info since it can be changed between instances
444 self.__stderr = _sys.stderr
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000445
446 def _set_daemon(self):
447 # Overridden in _MainThread and _DummyThread
Benjamin Petersoncbae8692008-08-18 17:45:09 +0000448 return current_thread().daemon
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000449
450 def __repr__(self):
451 assert self.__initialized, "Thread.__init__() was not called"
452 status = "initial"
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000453 if self.__started.is_set():
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000454 status = "started"
455 if self.__stopped:
456 status = "stopped"
457 if self.__daemonic:
Gregory P. Smith8856dda2008-06-01 23:48:47 +0000458 status += " daemon"
459 if self.__ident is not None:
460 status += " %s" % self.__ident
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000461 return "<%s(%s, %s)>" % (self.__class__.__name__, self.__name, status)
462
463 def start(self):
Collin Winter50b79ce2007-06-06 00:17:35 +0000464 if not self.__initialized:
465 raise RuntimeError("thread.__init__() not called")
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000466 if self.__started.is_set():
Collin Winter50b79ce2007-06-06 00:17:35 +0000467 raise RuntimeError("thread already started")
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000468 if __debug__:
469 self._note("%s.start(): starting thread", self)
Benjamin Petersonbd9dd312009-03-31 21:06:30 +0000470 with _active_limbo_lock:
471 _limbo[self] = self
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000472 _start_new_thread(self.__bootstrap, ())
Jeffrey Yasskin69e13092008-02-28 06:09:19 +0000473 self.__started.wait()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000474
475 def run(self):
Jeffrey Yasskina885c152008-02-23 20:40:35 +0000476 try:
477 if self.__target:
478 self.__target(*self.__args, **self.__kwargs)
479 finally:
480 # Avoid a refcycle if the thread is running a function with
481 # an argument that has a member that points to the thread.
482 del self.__target, self.__args, self.__kwargs
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000483
484 def __bootstrap(self):
Guido van Rossum54ec61e2007-08-20 15:18:04 +0000485 # Wrapper around the real bootstrap code that ignores
486 # exceptions during interpreter cleanup. Those typically
487 # happen when a daemon thread wakes up at an unfortunate
488 # moment, finds the world around it destroyed, and raises some
489 # random exception *** while trying to report the exception in
490 # __bootstrap_inner() below ***. Those random exceptions
491 # don't help anybody, and they confuse users, so we suppress
492 # them. We suppress them only when it appears that the world
493 # indeed has already been destroyed, so that exceptions in
494 # __bootstrap_inner() during normal business hours are properly
495 # reported. Also, we only suppress them for daemonic threads;
496 # if a non-daemonic encounters this, something else is wrong.
497 try:
498 self.__bootstrap_inner()
499 except:
500 if self.__daemonic and _sys is None:
501 return
502 raise
503
Benjamin Petersond906ea62009-03-31 21:34:42 +0000504 def _set_ident(self):
505 self.__ident = _get_ident()
506
Guido van Rossum54ec61e2007-08-20 15:18:04 +0000507 def __bootstrap_inner(self):
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000508 try:
Benjamin Petersond906ea62009-03-31 21:34:42 +0000509 self._set_ident()
Jeffrey Yasskin69e13092008-02-28 06:09:19 +0000510 self.__started.set()
Benjamin Petersonbd9dd312009-03-31 21:06:30 +0000511 with _active_limbo_lock:
512 _active[self.__ident] = self
513 del _limbo[self]
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000514 if __debug__:
515 self._note("%s.__bootstrap(): thread started", self)
Jeremy Hyltonbfccb352003-06-29 16:58:41 +0000516
517 if _trace_hook:
518 self._note("%s.__bootstrap(): registering trace hook", self)
519 _sys.settrace(_trace_hook)
520 if _profile_hook:
521 self._note("%s.__bootstrap(): registering profile hook", self)
522 _sys.setprofile(_profile_hook)
Tim Petersd1b108b2003-06-29 17:24:17 +0000523
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000524 try:
525 self.run()
526 except SystemExit:
527 if __debug__:
528 self._note("%s.__bootstrap(): raised SystemExit", self)
529 except:
530 if __debug__:
531 self._note("%s.__bootstrap(): unhandled exception", self)
Brett Cannoncc4e9352004-07-03 03:52:35 +0000532 # If sys.stderr is no more (most likely from interpreter
533 # shutdown) use self.__stderr. Otherwise still use sys (as in
534 # _sys) in case sys.stderr was redefined since the creation of
535 # self.
536 if _sys:
537 _sys.stderr.write("Exception in thread %s:\n%s\n" %
Benjamin Petersonb6a95562008-08-22 20:43:48 +0000538 (self.name, _format_exc()))
Brett Cannoncc4e9352004-07-03 03:52:35 +0000539 else:
540 # Do the best job possible w/o a huge amt. of code to
541 # approximate a traceback (code ideas from
542 # Lib/traceback.py)
543 exc_type, exc_value, exc_tb = self.__exc_info()
544 try:
545 print>>self.__stderr, (
Benjamin Petersonb6a95562008-08-22 20:43:48 +0000546 "Exception in thread " + self.name +
Brett Cannoncc4e9352004-07-03 03:52:35 +0000547 " (most likely raised during interpreter shutdown):")
548 print>>self.__stderr, (
549 "Traceback (most recent call last):")
550 while exc_tb:
551 print>>self.__stderr, (
552 ' File "%s", line %s, in %s' %
553 (exc_tb.tb_frame.f_code.co_filename,
554 exc_tb.tb_lineno,
555 exc_tb.tb_frame.f_code.co_name))
556 exc_tb = exc_tb.tb_next
557 print>>self.__stderr, ("%s: %s" % (exc_type, exc_value))
558 # Make sure that exc_tb gets deleted since it is a memory
559 # hog; deleting everything else is just for thoroughness
560 finally:
561 del exc_type, exc_value, exc_tb
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000562 else:
563 if __debug__:
564 self._note("%s.__bootstrap(): normal return", self)
Jeffrey Yasskin8b9091f2008-03-28 04:11:18 +0000565 finally:
566 # Prevent a race in
567 # test_threading.test_no_refcycle_through_target when
568 # the exception keeps the target alive past when we
569 # assert that it's dead.
Amaury Forgeot d'Arc504a48f2008-03-29 01:41:08 +0000570 self.__exc_clear()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000571 finally:
Gregory P. Smith95cd5c02008-01-22 01:20:42 +0000572 with _active_limbo_lock:
573 self.__stop()
574 try:
575 # We don't call self.__delete() because it also
576 # grabs _active_limbo_lock.
577 del _active[_get_ident()]
578 except:
579 pass
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000580
581 def __stop(self):
Raymond Hettinger70ec29d2008-01-24 18:12:23 +0000582 self.__block.acquire()
583 self.__stopped = True
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000584 self.__block.notify_all()
Raymond Hettinger70ec29d2008-01-24 18:12:23 +0000585 self.__block.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000586
587 def __delete(self):
Tim Peters21429932004-07-21 03:36:52 +0000588 "Remove current thread from the dict of currently running threads."
Brett Cannon8b3d92a2004-07-21 02:21:58 +0000589
Tim Peters21429932004-07-21 03:36:52 +0000590 # Notes about running with dummy_thread:
591 #
592 # Must take care to not raise an exception if dummy_thread is being
593 # used (and thus this module is being used as an instance of
594 # dummy_threading). dummy_thread.get_ident() always returns -1 since
595 # there is only one thread if dummy_thread is being used. Thus
596 # len(_active) is always <= 1 here, and any Thread instance created
597 # overwrites the (if any) thread currently registered in _active.
598 #
599 # An instance of _MainThread is always created by 'threading'. This
600 # gets overwritten the instant an instance of Thread is created; both
601 # threads return -1 from dummy_thread.get_ident() and thus have the
602 # same key in the dict. So when the _MainThread instance created by
603 # 'threading' tries to clean itself up when atexit calls this method
604 # it gets a KeyError if another Thread instance was created.
605 #
606 # This all means that KeyError from trying to delete something from
607 # _active if dummy_threading is being used is a red herring. But
608 # since it isn't if dummy_threading is *not* being used then don't
609 # hide the exception.
Brett Cannon8b3d92a2004-07-21 02:21:58 +0000610
Raymond Hettinger70ec29d2008-01-24 18:12:23 +0000611 try:
Amaury Forgeot d'Arcd7a26512008-04-03 23:07:55 +0000612 with _active_limbo_lock:
Brett Cannon8b3d92a2004-07-21 02:21:58 +0000613 del _active[_get_ident()]
Amaury Forgeot d'Arcd7a26512008-04-03 23:07:55 +0000614 # There must not be any python code between the previous line
615 # and after the lock is released. Otherwise a tracing function
616 # could try to acquire the lock again in the same thread, (in
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000617 # current_thread()), and would block.
Amaury Forgeot d'Arcd7a26512008-04-03 23:07:55 +0000618 except KeyError:
619 if 'dummy_threading' not in _sys.modules:
620 raise
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000621
622 def join(self, timeout=None):
Collin Winter50b79ce2007-06-06 00:17:35 +0000623 if not self.__initialized:
624 raise RuntimeError("Thread.__init__() not called")
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000625 if not self.__started.is_set():
Collin Winter50b79ce2007-06-06 00:17:35 +0000626 raise RuntimeError("cannot join thread before it is started")
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000627 if self is current_thread():
Collin Winter50b79ce2007-06-06 00:17:35 +0000628 raise RuntimeError("cannot join current thread")
629
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000630 if __debug__:
631 if not self.__stopped:
632 self._note("%s.join(): waiting until thread stops", self)
Raymond Hettinger70ec29d2008-01-24 18:12:23 +0000633 self.__block.acquire()
634 try:
Brett Cannonad07ff22005-11-23 02:15:50 +0000635 if timeout is None:
636 while not self.__stopped:
637 self.__block.wait()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000638 if __debug__:
639 self._note("%s.join(): thread stopped", self)
Brett Cannonad07ff22005-11-23 02:15:50 +0000640 else:
641 deadline = _time() + timeout
642 while not self.__stopped:
643 delay = deadline - _time()
644 if delay <= 0:
645 if __debug__:
646 self._note("%s.join(): timed out", self)
647 break
648 self.__block.wait(delay)
649 else:
650 if __debug__:
651 self._note("%s.join(): thread stopped", self)
Raymond Hettinger70ec29d2008-01-24 18:12:23 +0000652 finally:
653 self.__block.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000654
Benjamin Petersoncbae8692008-08-18 17:45:09 +0000655 @property
656 def name(self):
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000657 assert self.__initialized, "Thread.__init__() not called"
658 return self.__name
659
Benjamin Petersoncbae8692008-08-18 17:45:09 +0000660 @name.setter
661 def name(self, name):
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000662 assert self.__initialized, "Thread.__init__() not called"
663 self.__name = str(name)
664
Benjamin Petersond8a89722008-08-18 16:40:03 +0000665 @property
666 def ident(self):
Gregory P. Smith8856dda2008-06-01 23:48:47 +0000667 assert self.__initialized, "Thread.__init__() not called"
668 return self.__ident
669
Benjamin Peterson973e6c22008-09-01 23:12:58 +0000670 def isAlive(self):
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000671 assert self.__initialized, "Thread.__init__() not called"
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000672 return self.__started.is_set() and not self.__stopped
Tim Petersb90f89a2001-01-15 03:26:36 +0000673
Benjamin Peterson973e6c22008-09-01 23:12:58 +0000674 is_alive = isAlive
Benjamin Peterson6ee1a312008-08-18 21:53:29 +0000675
Benjamin Petersoncbae8692008-08-18 17:45:09 +0000676 @property
677 def daemon(self):
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000678 assert self.__initialized, "Thread.__init__() not called"
679 return self.__daemonic
680
Benjamin Petersoncbae8692008-08-18 17:45:09 +0000681 @daemon.setter
682 def daemon(self, daemonic):
Collin Winter50b79ce2007-06-06 00:17:35 +0000683 if not self.__initialized:
684 raise RuntimeError("Thread.__init__() not called")
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000685 if self.__started.is_set():
Collin Winter50b79ce2007-06-06 00:17:35 +0000686 raise RuntimeError("cannot set daemon status of active thread");
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000687 self.__daemonic = daemonic
688
Benjamin Petersond8106262008-08-18 18:13:17 +0000689 def isDaemon(self):
690 return self.daemon
691
692 def setDaemon(self, daemonic):
693 self.daemon = daemonic
694
695 def getName(self):
696 return self.name
697
698 def setName(self, name):
699 self.name = name
700
Martin v. Löwis44f86962001-09-05 13:44:54 +0000701# The timer class was contributed by Itamar Shtull-Trauring
702
703def Timer(*args, **kwargs):
704 return _Timer(*args, **kwargs)
705
706class _Timer(Thread):
707 """Call a function after a specified number of seconds:
Tim Petersb64bec32001-09-18 02:26:39 +0000708
Martin v. Löwis44f86962001-09-05 13:44:54 +0000709 t = Timer(30.0, f, args=[], kwargs={})
710 t.start()
711 t.cancel() # stop the timer's action if it's still waiting
712 """
Tim Petersb64bec32001-09-18 02:26:39 +0000713
Martin v. Löwis44f86962001-09-05 13:44:54 +0000714 def __init__(self, interval, function, args=[], kwargs={}):
715 Thread.__init__(self)
716 self.interval = interval
717 self.function = function
718 self.args = args
719 self.kwargs = kwargs
720 self.finished = Event()
Tim Petersb64bec32001-09-18 02:26:39 +0000721
Martin v. Löwis44f86962001-09-05 13:44:54 +0000722 def cancel(self):
723 """Stop the timer if it hasn't finished yet"""
724 self.finished.set()
Tim Petersb64bec32001-09-18 02:26:39 +0000725
Martin v. Löwis44f86962001-09-05 13:44:54 +0000726 def run(self):
727 self.finished.wait(self.interval)
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000728 if not self.finished.is_set():
Martin v. Löwis44f86962001-09-05 13:44:54 +0000729 self.function(*self.args, **self.kwargs)
730 self.finished.set()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000731
732# Special thread class to represent the main thread
733# This is garbage collected through an exit handler
734
735class _MainThread(Thread):
736
737 def __init__(self):
738 Thread.__init__(self, name="MainThread")
Jeffrey Yasskin69e13092008-02-28 06:09:19 +0000739 self._Thread__started.set()
Benjamin Petersond906ea62009-03-31 21:34:42 +0000740 self._set_ident()
Benjamin Petersonbd9dd312009-03-31 21:06:30 +0000741 with _active_limbo_lock:
742 _active[_get_ident()] = self
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000743
744 def _set_daemon(self):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000745 return False
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000746
Martin v. Löwis7b7c9d42007-01-04 21:06:12 +0000747 def _exitfunc(self):
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000748 self._Thread__stop()
749 t = _pickSomeNonDaemonThread()
750 if t:
751 if __debug__:
752 self._note("%s: waiting for other threads", self)
753 while t:
754 t.join()
755 t = _pickSomeNonDaemonThread()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000756 if __debug__:
757 self._note("%s: exiting", self)
758 self._Thread__delete()
759
760def _pickSomeNonDaemonThread():
761 for t in enumerate():
Benjamin Petersoncbae8692008-08-18 17:45:09 +0000762 if not t.daemon and t.is_alive():
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000763 return t
764 return None
765
766
767# Dummy thread class to represent threads not started here.
Tim Peters711906e2005-01-08 07:30:42 +0000768# These aren't garbage collected when they die, nor can they be waited for.
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000769# If they invoke anything in threading.py that calls current_thread(), they
Tim Peters711906e2005-01-08 07:30:42 +0000770# leave an entry in the _active dict forever after.
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000771# Their purpose is to return *something* from current_thread().
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000772# They are marked as daemon threads so we won't wait for them
773# when we exit (conform previous semantics).
774
775class _DummyThread(Thread):
Tim Petersb90f89a2001-01-15 03:26:36 +0000776
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000777 def __init__(self):
778 Thread.__init__(self, name=_newname("Dummy-%d"))
Tim Peters711906e2005-01-08 07:30:42 +0000779
780 # Thread.__block consumes an OS-level locking primitive, which
781 # can never be used by a _DummyThread. Since a _DummyThread
782 # instance is immortal, that's bad, so release this resource.
Brett Cannone6539c42005-01-08 02:43:53 +0000783 del self._Thread__block
Tim Peters711906e2005-01-08 07:30:42 +0000784
Jeffrey Yasskin69e13092008-02-28 06:09:19 +0000785 self._Thread__started.set()
Benjamin Petersond906ea62009-03-31 21:34:42 +0000786 self._set_ident()
Benjamin Petersonbd9dd312009-03-31 21:06:30 +0000787 with _active_limbo_lock:
788 _active[_get_ident()] = self
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000789
790 def _set_daemon(self):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000791 return True
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000792
Neal Norwitz45bec8c2002-02-19 03:01:36 +0000793 def join(self, timeout=None):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000794 assert False, "cannot join a dummy thread"
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000795
796
797# Global API functions
798
Benjamin Peterson973e6c22008-09-01 23:12:58 +0000799def currentThread():
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000800 try:
801 return _active[_get_ident()]
802 except KeyError:
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000803 ##print "current_thread(): no current thread for", _get_ident()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000804 return _DummyThread()
805
Benjamin Peterson973e6c22008-09-01 23:12:58 +0000806current_thread = currentThread
Benjamin Petersonf4395602008-06-11 17:50:00 +0000807
Benjamin Peterson973e6c22008-09-01 23:12:58 +0000808def activeCount():
Benjamin Petersonbd9dd312009-03-31 21:06:30 +0000809 with _active_limbo_lock:
810 return len(_active) + len(_limbo)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000811
Benjamin Peterson973e6c22008-09-01 23:12:58 +0000812active_count = activeCount
Benjamin Petersonf4395602008-06-11 17:50:00 +0000813
Antoine Pitrou99c160b2009-11-05 13:42:29 +0000814def _enumerate():
815 # Same as enumerate(), but without the lock. Internal use only.
816 return _active.values() + _limbo.values()
817
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000818def enumerate():
Benjamin Petersonbd9dd312009-03-31 21:06:30 +0000819 with _active_limbo_lock:
820 return _active.values() + _limbo.values()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000821
Andrew MacIntyre92913322006-06-13 15:04:24 +0000822from thread import stack_size
823
Martin v. Löwis7b7c9d42007-01-04 21:06:12 +0000824# Create the main thread object,
825# and make it available for the interpreter
826# (Py_Main) as threading._shutdown.
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000827
Martin v. Löwis7b7c9d42007-01-04 21:06:12 +0000828_shutdown = _MainThread()._exitfunc
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000829
Jim Fultond15dc062004-07-14 19:11:50 +0000830# get thread-local implementation, either from the thread
831# module, or from the python fallback
832
833try:
834 from thread import _local as local
835except ImportError:
836 from _threading_local import local
837
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000838
Jesse Noller5e62ca42008-07-16 20:03:47 +0000839def _after_fork():
840 # This function is called by Python/ceval.c:PyEval_ReInitThreads which
841 # is called from PyOS_AfterFork. Here we cleanup threading module state
842 # that should not exist after a fork.
843
844 # Reset _active_limbo_lock, in case we forked while the lock was held
845 # by another (non-forked) thread. http://bugs.python.org/issue874900
846 global _active_limbo_lock
847 _active_limbo_lock = _allocate_lock()
848
849 # fork() only copied the current thread; clear references to others.
850 new_active = {}
851 current = current_thread()
852 with _active_limbo_lock:
Antoine Pitrou9fb1aca2008-09-06 23:04:32 +0000853 for thread in _active.itervalues():
Jesse Noller5e62ca42008-07-16 20:03:47 +0000854 if thread is current:
Antoine Pitrou9fb1aca2008-09-06 23:04:32 +0000855 # There is only one active thread. We reset the ident to
856 # its new value since it can have changed.
857 ident = _get_ident()
858 thread._Thread__ident = ident
Jesse Noller5e62ca42008-07-16 20:03:47 +0000859 new_active[ident] = thread
860 else:
861 # All the others are already stopped.
862 # We don't call _Thread__stop() because it tries to acquire
863 # thread._Thread__block which could also have been held while
864 # we forked.
865 thread._Thread__stopped = True
866
867 _limbo.clear()
868 _active.clear()
869 _active.update(new_active)
870 assert len(_active) == 1
871
872
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000873# Self-test code
874
875def _test():
876
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000877 class BoundedQueue(_Verbose):
878
879 def __init__(self, limit):
880 _Verbose.__init__(self)
881 self.mon = RLock()
882 self.rc = Condition(self.mon)
883 self.wc = Condition(self.mon)
884 self.limit = limit
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000885 self.queue = deque()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000886
887 def put(self, item):
888 self.mon.acquire()
889 while len(self.queue) >= self.limit:
890 self._note("put(%s): queue full", item)
891 self.wc.wait()
892 self.queue.append(item)
893 self._note("put(%s): appended, length now %d",
894 item, len(self.queue))
895 self.rc.notify()
896 self.mon.release()
897
898 def get(self):
899 self.mon.acquire()
900 while not self.queue:
901 self._note("get(): queue empty")
902 self.rc.wait()
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000903 item = self.queue.popleft()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000904 self._note("get(): got %s, %d left", item, len(self.queue))
905 self.wc.notify()
906 self.mon.release()
907 return item
908
909 class ProducerThread(Thread):
910
911 def __init__(self, queue, quota):
912 Thread.__init__(self, name="Producer")
913 self.queue = queue
914 self.quota = quota
915
916 def run(self):
Guido van Rossumb26a1b41998-05-20 17:05:52 +0000917 from random import random
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000918 counter = 0
919 while counter < self.quota:
920 counter = counter + 1
Benjamin Petersoncbae8692008-08-18 17:45:09 +0000921 self.queue.put("%s.%d" % (self.name, counter))
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000922 _sleep(random() * 0.00001)
923
924
925 class ConsumerThread(Thread):
926
927 def __init__(self, queue, count):
928 Thread.__init__(self, name="Consumer")
929 self.queue = queue
930 self.count = count
931
932 def run(self):
933 while self.count > 0:
934 item = self.queue.get()
935 print item
936 self.count = self.count - 1
937
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000938 NP = 3
939 QL = 4
940 NI = 5
941
942 Q = BoundedQueue(QL)
943 P = []
944 for i in range(NP):
945 t = ProducerThread(Q, NI)
Benjamin Petersoncbae8692008-08-18 17:45:09 +0000946 t.name = ("Producer-%d" % (i+1))
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000947 P.append(t)
948 C = ConsumerThread(Q, NI*NP)
949 for t in P:
950 t.start()
951 _sleep(0.000001)
952 C.start()
953 for t in P:
954 t.join()
955 C.join()
956
957if __name__ == '__main__':
958 _test()