blob: 28a8a2f946e2e978f4e4277a6a302ec282661891 [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
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000109 return "<%s(%s, %d)>" % (
110 self.__class__.__name__,
Benjamin Petersonb6a95562008-08-22 20:43:48 +0000111 owner and owner.name,
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000112 self.__count)
113
114 def acquire(self, blocking=1):
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000115 me = current_thread()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000116 if self.__owner is me:
117 self.__count = self.__count + 1
118 if __debug__:
119 self._note("%s.acquire(%s): recursive success", self, blocking)
120 return 1
121 rc = self.__block.acquire(blocking)
122 if rc:
123 self.__owner = me
124 self.__count = 1
125 if __debug__:
Brett Cannon90cece72005-01-27 22:48:30 +0000126 self._note("%s.acquire(%s): initial success", self, blocking)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000127 else:
128 if __debug__:
129 self._note("%s.acquire(%s): failure", self, blocking)
130 return rc
131
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000132 __enter__ = acquire
133
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000134 def release(self):
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000135 if self.__owner is not current_thread():
Collin Winter50b79ce2007-06-06 00:17:35 +0000136 raise RuntimeError("cannot release un-aquired lock")
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000137 self.__count = count = self.__count - 1
138 if not count:
139 self.__owner = None
140 self.__block.release()
141 if __debug__:
142 self._note("%s.release(): final release", self)
143 else:
144 if __debug__:
145 self._note("%s.release(): non-final release", self)
146
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000147 def __exit__(self, t, v, tb):
148 self.release()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000149
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000150 # Internal methods used by condition variables
151
Brett Cannon20050502008-08-02 03:13:46 +0000152 def _acquire_restore(self, count_owner):
153 count, owner = count_owner
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000154 self.__block.acquire()
155 self.__count = count
156 self.__owner = owner
157 if __debug__:
158 self._note("%s._acquire_restore()", self)
159
160 def _release_save(self):
161 if __debug__:
162 self._note("%s._release_save()", self)
163 count = self.__count
164 self.__count = 0
165 owner = self.__owner
166 self.__owner = None
167 self.__block.release()
168 return (count, owner)
169
170 def _is_owned(self):
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000171 return self.__owner is current_thread()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000172
173
174def Condition(*args, **kwargs):
Guido van Rossum68468eb2003-02-27 20:14:51 +0000175 return _Condition(*args, **kwargs)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000176
177class _Condition(_Verbose):
178
179 def __init__(self, lock=None, verbose=None):
180 _Verbose.__init__(self, verbose)
181 if lock is None:
182 lock = RLock()
183 self.__lock = lock
184 # Export the lock's acquire() and release() methods
185 self.acquire = lock.acquire
186 self.release = lock.release
187 # If the lock defines _release_save() and/or _acquire_restore(),
188 # these override the default implementations (which just call
189 # release() and acquire() on the lock). Ditto for _is_owned().
190 try:
191 self._release_save = lock._release_save
192 except AttributeError:
193 pass
194 try:
195 self._acquire_restore = lock._acquire_restore
196 except AttributeError:
197 pass
198 try:
199 self._is_owned = lock._is_owned
200 except AttributeError:
201 pass
202 self.__waiters = []
203
Guido van Rossumda5b7012006-05-02 19:47:52 +0000204 def __enter__(self):
205 return self.__lock.__enter__()
206
207 def __exit__(self, *args):
208 return self.__lock.__exit__(*args)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000209
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000210 def __repr__(self):
211 return "<Condition(%s, %d)>" % (self.__lock, len(self.__waiters))
212
213 def _release_save(self):
214 self.__lock.release() # No state to save
215
216 def _acquire_restore(self, x):
217 self.__lock.acquire() # Ignore saved state
218
219 def _is_owned(self):
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000220 # Return True if lock is owned by current_thread.
Jeremy Hyltonaf7fde72002-08-14 17:43:59 +0000221 # This method is called only if __lock doesn't have _is_owned().
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000222 if self.__lock.acquire(0):
223 self.__lock.release()
Tim Petersbc0e9102002-04-04 22:55:58 +0000224 return False
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000225 else:
Tim Petersbc0e9102002-04-04 22:55:58 +0000226 return True
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000227
228 def wait(self, timeout=None):
Collin Winter50b79ce2007-06-06 00:17:35 +0000229 if not self._is_owned():
230 raise RuntimeError("cannot wait on un-aquired lock")
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000231 waiter = _allocate_lock()
232 waiter.acquire()
233 self.__waiters.append(waiter)
234 saved_state = self._release_save()
Tim Petersc951bf92001-04-02 20:15:57 +0000235 try: # restore state no matter what (e.g., KeyboardInterrupt)
236 if timeout is None:
237 waiter.acquire()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000238 if __debug__:
Tim Petersc951bf92001-04-02 20:15:57 +0000239 self._note("%s.wait(): got it", self)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000240 else:
Tim Petersa6a4f272001-08-12 00:41:33 +0000241 # Balancing act: We can't afford a pure busy loop, so we
242 # have to sleep; but if we sleep the whole timeout time,
243 # we'll be unresponsive. The scheme here sleeps very
244 # little at first, longer as time goes on, but never longer
245 # than 20 times per second (or the timeout time remaining).
Tim Petersc951bf92001-04-02 20:15:57 +0000246 endtime = _time() + timeout
Tim Petersa6a4f272001-08-12 00:41:33 +0000247 delay = 0.0005 # 500 us -> initial delay of 1 ms
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000248 while True:
Tim Petersc951bf92001-04-02 20:15:57 +0000249 gotit = waiter.acquire(0)
Tim Petersa6a4f272001-08-12 00:41:33 +0000250 if gotit:
Tim Petersc951bf92001-04-02 20:15:57 +0000251 break
Tim Petersa6a4f272001-08-12 00:41:33 +0000252 remaining = endtime - _time()
253 if remaining <= 0:
254 break
255 delay = min(delay * 2, remaining, .05)
Tim Petersc951bf92001-04-02 20:15:57 +0000256 _sleep(delay)
Tim Petersc951bf92001-04-02 20:15:57 +0000257 if not gotit:
258 if __debug__:
259 self._note("%s.wait(%s): timed out", self, timeout)
260 try:
261 self.__waiters.remove(waiter)
262 except ValueError:
263 pass
264 else:
265 if __debug__:
266 self._note("%s.wait(%s): got it", self, timeout)
267 finally:
268 self._acquire_restore(saved_state)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000269
270 def notify(self, n=1):
Collin Winter50b79ce2007-06-06 00:17:35 +0000271 if not self._is_owned():
272 raise RuntimeError("cannot notify on un-aquired lock")
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000273 __waiters = self.__waiters
274 waiters = __waiters[:n]
275 if not waiters:
276 if __debug__:
277 self._note("%s.notify(): no waiters", self)
278 return
279 self._note("%s.notify(): notifying %d waiter%s", self, n,
280 n!=1 and "s" or "")
281 for waiter in waiters:
282 waiter.release()
283 try:
284 __waiters.remove(waiter)
285 except ValueError:
286 pass
287
Benjamin Peterson973e6c22008-09-01 23:12:58 +0000288 def notifyAll(self):
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000289 self.notify(len(self.__waiters))
290
Benjamin Peterson973e6c22008-09-01 23:12:58 +0000291 notify_all = notifyAll
Benjamin Petersonf4395602008-06-11 17:50:00 +0000292
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000293
294def Semaphore(*args, **kwargs):
Guido van Rossum68468eb2003-02-27 20:14:51 +0000295 return _Semaphore(*args, **kwargs)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000296
297class _Semaphore(_Verbose):
298
Andrew M. Kuchling39d3bfc2000-02-29 00:10:24 +0000299 # After Tim Peters' semaphore class, but not quite the same (no maximum)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000300
301 def __init__(self, value=1, verbose=None):
Collin Winter50b79ce2007-06-06 00:17:35 +0000302 if value < 0:
303 raise ValueError("semaphore initial value must be >= 0")
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000304 _Verbose.__init__(self, verbose)
305 self.__cond = Condition(Lock())
306 self.__value = value
307
308 def acquire(self, blocking=1):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000309 rc = False
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000310 self.__cond.acquire()
311 while self.__value == 0:
312 if not blocking:
313 break
Skip Montanarob446fc72001-08-19 04:25:24 +0000314 if __debug__:
315 self._note("%s.acquire(%s): blocked waiting, value=%s",
316 self, blocking, self.__value)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000317 self.__cond.wait()
318 else:
319 self.__value = self.__value - 1
Skip Montanarob446fc72001-08-19 04:25:24 +0000320 if __debug__:
Skip Montanaroae8454a2001-08-19 05:53:47 +0000321 self._note("%s.acquire: success, value=%s",
322 self, self.__value)
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000323 rc = True
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000324 self.__cond.release()
325 return rc
326
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000327 __enter__ = acquire
328
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000329 def release(self):
330 self.__cond.acquire()
331 self.__value = self.__value + 1
Skip Montanarob446fc72001-08-19 04:25:24 +0000332 if __debug__:
Skip Montanaroae8454a2001-08-19 05:53:47 +0000333 self._note("%s.release: success, value=%s",
334 self, self.__value)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000335 self.__cond.notify()
336 self.__cond.release()
337
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000338 def __exit__(self, t, v, tb):
339 self.release()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000340
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000341
Skip Montanaroe428bb72001-08-20 20:27:58 +0000342def BoundedSemaphore(*args, **kwargs):
Guido van Rossum68468eb2003-02-27 20:14:51 +0000343 return _BoundedSemaphore(*args, **kwargs)
Skip Montanaroe428bb72001-08-20 20:27:58 +0000344
345class _BoundedSemaphore(_Semaphore):
346 """Semaphore that checks that # releases is <= # acquires"""
347 def __init__(self, value=1, verbose=None):
348 _Semaphore.__init__(self, value, verbose)
349 self._initial_value = value
350
351 def release(self):
352 if self._Semaphore__value >= self._initial_value:
353 raise ValueError, "Semaphore released too many times"
354 return _Semaphore.release(self)
355
356
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000357def Event(*args, **kwargs):
Guido van Rossum68468eb2003-02-27 20:14:51 +0000358 return _Event(*args, **kwargs)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000359
360class _Event(_Verbose):
361
362 # After Tim Peters' event class (without is_posted())
363
364 def __init__(self, verbose=None):
365 _Verbose.__init__(self, verbose)
366 self.__cond = Condition(Lock())
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000367 self.__flag = False
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000368
Benjamin Peterson973e6c22008-09-01 23:12:58 +0000369 def isSet(self):
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000370 return self.__flag
371
Benjamin Peterson973e6c22008-09-01 23:12:58 +0000372 is_set = isSet
Benjamin Petersonf4395602008-06-11 17:50:00 +0000373
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000374 def set(self):
Raymond Hettinger70ec29d2008-01-24 18:12:23 +0000375 self.__cond.acquire()
376 try:
Guido van Rossum21b60142002-11-21 21:08:39 +0000377 self.__flag = True
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000378 self.__cond.notify_all()
Raymond Hettinger70ec29d2008-01-24 18:12:23 +0000379 finally:
380 self.__cond.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000381
382 def clear(self):
Raymond Hettinger70ec29d2008-01-24 18:12:23 +0000383 self.__cond.acquire()
384 try:
Guido van Rossum21b60142002-11-21 21:08:39 +0000385 self.__flag = False
Raymond Hettinger70ec29d2008-01-24 18:12:23 +0000386 finally:
387 self.__cond.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000388
389 def wait(self, timeout=None):
Raymond Hettinger70ec29d2008-01-24 18:12:23 +0000390 self.__cond.acquire()
391 try:
Guido van Rossum21b60142002-11-21 21:08:39 +0000392 if not self.__flag:
393 self.__cond.wait(timeout)
Georg Brandlef660e82009-03-31 20:41:08 +0000394 return self.__flag
Raymond Hettinger70ec29d2008-01-24 18:12:23 +0000395 finally:
396 self.__cond.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000397
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000398# Helper to generate new thread names
399_counter = 0
400def _newname(template="Thread-%d"):
401 global _counter
402 _counter = _counter + 1
403 return template % _counter
404
405# Active thread administration
406_active_limbo_lock = _allocate_lock()
Tim Peters711906e2005-01-08 07:30:42 +0000407_active = {} # maps thread id to Thread object
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000408_limbo = {}
409
410
411# Main class for threads
412
413class Thread(_Verbose):
414
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000415 __initialized = False
Brett Cannoncc4e9352004-07-03 03:52:35 +0000416 # Need to store a reference to sys.exc_info for printing
417 # out exceptions when a thread tries to use a global var. during interp.
418 # shutdown and thus raises an exception about trying to perform some
419 # operation on/with a NoneType
420 __exc_info = _sys.exc_info
Jeffrey Yasskin8b9091f2008-03-28 04:11:18 +0000421 # Keep sys.exc_clear too to clear the exception just before
422 # allowing .join() to return.
423 __exc_clear = _sys.exc_clear
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000424
425 def __init__(self, group=None, target=None, name=None,
Georg Brandla4a8b822005-07-15 09:13:21 +0000426 args=(), kwargs=None, verbose=None):
Guido van Rossum5a43e1a1998-06-09 19:04:26 +0000427 assert group is None, "group argument must be None for now"
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000428 _Verbose.__init__(self, verbose)
Georg Brandla4a8b822005-07-15 09:13:21 +0000429 if kwargs is None:
430 kwargs = {}
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000431 self.__target = target
432 self.__name = str(name or _newname())
433 self.__args = args
434 self.__kwargs = kwargs
435 self.__daemonic = self._set_daemon()
Gregory P. Smith8856dda2008-06-01 23:48:47 +0000436 self.__ident = None
Jeffrey Yasskin69e13092008-02-28 06:09:19 +0000437 self.__started = Event()
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000438 self.__stopped = False
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000439 self.__block = Condition(Lock())
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000440 self.__initialized = True
Brett Cannoncc4e9352004-07-03 03:52:35 +0000441 # sys.stderr is not stored in the class like
442 # sys.exc_info since it can be changed between instances
443 self.__stderr = _sys.stderr
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000444
445 def _set_daemon(self):
446 # Overridden in _MainThread and _DummyThread
Benjamin Petersoncbae8692008-08-18 17:45:09 +0000447 return current_thread().daemon
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000448
449 def __repr__(self):
450 assert self.__initialized, "Thread.__init__() was not called"
451 status = "initial"
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000452 if self.__started.is_set():
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000453 status = "started"
454 if self.__stopped:
455 status = "stopped"
456 if self.__daemonic:
Gregory P. Smith8856dda2008-06-01 23:48:47 +0000457 status += " daemon"
458 if self.__ident is not None:
459 status += " %s" % self.__ident
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000460 return "<%s(%s, %s)>" % (self.__class__.__name__, self.__name, status)
461
462 def start(self):
Collin Winter50b79ce2007-06-06 00:17:35 +0000463 if not self.__initialized:
464 raise RuntimeError("thread.__init__() not called")
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000465 if self.__started.is_set():
Collin Winter50b79ce2007-06-06 00:17:35 +0000466 raise RuntimeError("thread already started")
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000467 if __debug__:
468 self._note("%s.start(): starting thread", self)
Benjamin Petersonbd9dd312009-03-31 21:06:30 +0000469 with _active_limbo_lock:
470 _limbo[self] = self
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000471 _start_new_thread(self.__bootstrap, ())
Jeffrey Yasskin69e13092008-02-28 06:09:19 +0000472 self.__started.wait()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000473
474 def run(self):
Jeffrey Yasskina885c152008-02-23 20:40:35 +0000475 try:
476 if self.__target:
477 self.__target(*self.__args, **self.__kwargs)
478 finally:
479 # Avoid a refcycle if the thread is running a function with
480 # an argument that has a member that points to the thread.
481 del self.__target, self.__args, self.__kwargs
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000482
483 def __bootstrap(self):
Guido van Rossum54ec61e2007-08-20 15:18:04 +0000484 # Wrapper around the real bootstrap code that ignores
485 # exceptions during interpreter cleanup. Those typically
486 # happen when a daemon thread wakes up at an unfortunate
487 # moment, finds the world around it destroyed, and raises some
488 # random exception *** while trying to report the exception in
489 # __bootstrap_inner() below ***. Those random exceptions
490 # don't help anybody, and they confuse users, so we suppress
491 # them. We suppress them only when it appears that the world
492 # indeed has already been destroyed, so that exceptions in
493 # __bootstrap_inner() during normal business hours are properly
494 # reported. Also, we only suppress them for daemonic threads;
495 # if a non-daemonic encounters this, something else is wrong.
496 try:
497 self.__bootstrap_inner()
498 except:
499 if self.__daemonic and _sys is None:
500 return
501 raise
502
503 def __bootstrap_inner(self):
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000504 try:
Gregory P. Smith8856dda2008-06-01 23:48:47 +0000505 self.__ident = _get_ident()
Jeffrey Yasskin69e13092008-02-28 06:09:19 +0000506 self.__started.set()
Benjamin Petersonbd9dd312009-03-31 21:06:30 +0000507 with _active_limbo_lock:
508 _active[self.__ident] = self
509 del _limbo[self]
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000510 if __debug__:
511 self._note("%s.__bootstrap(): thread started", self)
Jeremy Hyltonbfccb352003-06-29 16:58:41 +0000512
513 if _trace_hook:
514 self._note("%s.__bootstrap(): registering trace hook", self)
515 _sys.settrace(_trace_hook)
516 if _profile_hook:
517 self._note("%s.__bootstrap(): registering profile hook", self)
518 _sys.setprofile(_profile_hook)
Tim Petersd1b108b2003-06-29 17:24:17 +0000519
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000520 try:
521 self.run()
522 except SystemExit:
523 if __debug__:
524 self._note("%s.__bootstrap(): raised SystemExit", self)
525 except:
526 if __debug__:
527 self._note("%s.__bootstrap(): unhandled exception", self)
Brett Cannoncc4e9352004-07-03 03:52:35 +0000528 # If sys.stderr is no more (most likely from interpreter
529 # shutdown) use self.__stderr. Otherwise still use sys (as in
530 # _sys) in case sys.stderr was redefined since the creation of
531 # self.
532 if _sys:
533 _sys.stderr.write("Exception in thread %s:\n%s\n" %
Benjamin Petersonb6a95562008-08-22 20:43:48 +0000534 (self.name, _format_exc()))
Brett Cannoncc4e9352004-07-03 03:52:35 +0000535 else:
536 # Do the best job possible w/o a huge amt. of code to
537 # approximate a traceback (code ideas from
538 # Lib/traceback.py)
539 exc_type, exc_value, exc_tb = self.__exc_info()
540 try:
541 print>>self.__stderr, (
Benjamin Petersonb6a95562008-08-22 20:43:48 +0000542 "Exception in thread " + self.name +
Brett Cannoncc4e9352004-07-03 03:52:35 +0000543 " (most likely raised during interpreter shutdown):")
544 print>>self.__stderr, (
545 "Traceback (most recent call last):")
546 while exc_tb:
547 print>>self.__stderr, (
548 ' File "%s", line %s, in %s' %
549 (exc_tb.tb_frame.f_code.co_filename,
550 exc_tb.tb_lineno,
551 exc_tb.tb_frame.f_code.co_name))
552 exc_tb = exc_tb.tb_next
553 print>>self.__stderr, ("%s: %s" % (exc_type, exc_value))
554 # Make sure that exc_tb gets deleted since it is a memory
555 # hog; deleting everything else is just for thoroughness
556 finally:
557 del exc_type, exc_value, exc_tb
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000558 else:
559 if __debug__:
560 self._note("%s.__bootstrap(): normal return", self)
Jeffrey Yasskin8b9091f2008-03-28 04:11:18 +0000561 finally:
562 # Prevent a race in
563 # test_threading.test_no_refcycle_through_target when
564 # the exception keeps the target alive past when we
565 # assert that it's dead.
Amaury Forgeot d'Arc504a48f2008-03-29 01:41:08 +0000566 self.__exc_clear()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000567 finally:
Gregory P. Smith95cd5c02008-01-22 01:20:42 +0000568 with _active_limbo_lock:
569 self.__stop()
570 try:
571 # We don't call self.__delete() because it also
572 # grabs _active_limbo_lock.
573 del _active[_get_ident()]
574 except:
575 pass
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000576
577 def __stop(self):
Raymond Hettinger70ec29d2008-01-24 18:12:23 +0000578 self.__block.acquire()
579 self.__stopped = True
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000580 self.__block.notify_all()
Raymond Hettinger70ec29d2008-01-24 18:12:23 +0000581 self.__block.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000582
583 def __delete(self):
Tim Peters21429932004-07-21 03:36:52 +0000584 "Remove current thread from the dict of currently running threads."
Brett Cannon8b3d92a2004-07-21 02:21:58 +0000585
Tim Peters21429932004-07-21 03:36:52 +0000586 # Notes about running with dummy_thread:
587 #
588 # Must take care to not raise an exception if dummy_thread is being
589 # used (and thus this module is being used as an instance of
590 # dummy_threading). dummy_thread.get_ident() always returns -1 since
591 # there is only one thread if dummy_thread is being used. Thus
592 # len(_active) is always <= 1 here, and any Thread instance created
593 # overwrites the (if any) thread currently registered in _active.
594 #
595 # An instance of _MainThread is always created by 'threading'. This
596 # gets overwritten the instant an instance of Thread is created; both
597 # threads return -1 from dummy_thread.get_ident() and thus have the
598 # same key in the dict. So when the _MainThread instance created by
599 # 'threading' tries to clean itself up when atexit calls this method
600 # it gets a KeyError if another Thread instance was created.
601 #
602 # This all means that KeyError from trying to delete something from
603 # _active if dummy_threading is being used is a red herring. But
604 # since it isn't if dummy_threading is *not* being used then don't
605 # hide the exception.
Brett Cannon8b3d92a2004-07-21 02:21:58 +0000606
Raymond Hettinger70ec29d2008-01-24 18:12:23 +0000607 try:
Amaury Forgeot d'Arcd7a26512008-04-03 23:07:55 +0000608 with _active_limbo_lock:
Brett Cannon8b3d92a2004-07-21 02:21:58 +0000609 del _active[_get_ident()]
Amaury Forgeot d'Arcd7a26512008-04-03 23:07:55 +0000610 # There must not be any python code between the previous line
611 # and after the lock is released. Otherwise a tracing function
612 # could try to acquire the lock again in the same thread, (in
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000613 # current_thread()), and would block.
Amaury Forgeot d'Arcd7a26512008-04-03 23:07:55 +0000614 except KeyError:
615 if 'dummy_threading' not in _sys.modules:
616 raise
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000617
618 def join(self, timeout=None):
Collin Winter50b79ce2007-06-06 00:17:35 +0000619 if not self.__initialized:
620 raise RuntimeError("Thread.__init__() not called")
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000621 if not self.__started.is_set():
Collin Winter50b79ce2007-06-06 00:17:35 +0000622 raise RuntimeError("cannot join thread before it is started")
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000623 if self is current_thread():
Collin Winter50b79ce2007-06-06 00:17:35 +0000624 raise RuntimeError("cannot join current thread")
625
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000626 if __debug__:
627 if not self.__stopped:
628 self._note("%s.join(): waiting until thread stops", self)
Raymond Hettinger70ec29d2008-01-24 18:12:23 +0000629 self.__block.acquire()
630 try:
Brett Cannonad07ff22005-11-23 02:15:50 +0000631 if timeout is None:
632 while not self.__stopped:
633 self.__block.wait()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000634 if __debug__:
635 self._note("%s.join(): thread stopped", self)
Brett Cannonad07ff22005-11-23 02:15:50 +0000636 else:
637 deadline = _time() + timeout
638 while not self.__stopped:
639 delay = deadline - _time()
640 if delay <= 0:
641 if __debug__:
642 self._note("%s.join(): timed out", self)
643 break
644 self.__block.wait(delay)
645 else:
646 if __debug__:
647 self._note("%s.join(): thread stopped", self)
Raymond Hettinger70ec29d2008-01-24 18:12:23 +0000648 finally:
649 self.__block.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000650
Benjamin Petersoncbae8692008-08-18 17:45:09 +0000651 @property
652 def name(self):
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000653 assert self.__initialized, "Thread.__init__() not called"
654 return self.__name
655
Benjamin Petersoncbae8692008-08-18 17:45:09 +0000656 @name.setter
657 def name(self, name):
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000658 assert self.__initialized, "Thread.__init__() not called"
659 self.__name = str(name)
660
Benjamin Petersond8a89722008-08-18 16:40:03 +0000661 @property
662 def ident(self):
Gregory P. Smith8856dda2008-06-01 23:48:47 +0000663 assert self.__initialized, "Thread.__init__() not called"
664 return self.__ident
665
Benjamin Peterson973e6c22008-09-01 23:12:58 +0000666 def isAlive(self):
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000667 assert self.__initialized, "Thread.__init__() not called"
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000668 return self.__started.is_set() and not self.__stopped
Tim Petersb90f89a2001-01-15 03:26:36 +0000669
Benjamin Peterson973e6c22008-09-01 23:12:58 +0000670 is_alive = isAlive
Benjamin Peterson6ee1a312008-08-18 21:53:29 +0000671
Benjamin Petersoncbae8692008-08-18 17:45:09 +0000672 @property
673 def daemon(self):
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000674 assert self.__initialized, "Thread.__init__() not called"
675 return self.__daemonic
676
Benjamin Petersoncbae8692008-08-18 17:45:09 +0000677 @daemon.setter
678 def daemon(self, daemonic):
Collin Winter50b79ce2007-06-06 00:17:35 +0000679 if not self.__initialized:
680 raise RuntimeError("Thread.__init__() not called")
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000681 if self.__started.is_set():
Collin Winter50b79ce2007-06-06 00:17:35 +0000682 raise RuntimeError("cannot set daemon status of active thread");
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000683 self.__daemonic = daemonic
684
Benjamin Petersond8106262008-08-18 18:13:17 +0000685 def isDaemon(self):
686 return self.daemon
687
688 def setDaemon(self, daemonic):
689 self.daemon = daemonic
690
691 def getName(self):
692 return self.name
693
694 def setName(self, name):
695 self.name = name
696
Martin v. Löwis44f86962001-09-05 13:44:54 +0000697# The timer class was contributed by Itamar Shtull-Trauring
698
699def Timer(*args, **kwargs):
700 return _Timer(*args, **kwargs)
701
702class _Timer(Thread):
703 """Call a function after a specified number of seconds:
Tim Petersb64bec32001-09-18 02:26:39 +0000704
Martin v. Löwis44f86962001-09-05 13:44:54 +0000705 t = Timer(30.0, f, args=[], kwargs={})
706 t.start()
707 t.cancel() # stop the timer's action if it's still waiting
708 """
Tim Petersb64bec32001-09-18 02:26:39 +0000709
Martin v. Löwis44f86962001-09-05 13:44:54 +0000710 def __init__(self, interval, function, args=[], kwargs={}):
711 Thread.__init__(self)
712 self.interval = interval
713 self.function = function
714 self.args = args
715 self.kwargs = kwargs
716 self.finished = Event()
Tim Petersb64bec32001-09-18 02:26:39 +0000717
Martin v. Löwis44f86962001-09-05 13:44:54 +0000718 def cancel(self):
719 """Stop the timer if it hasn't finished yet"""
720 self.finished.set()
Tim Petersb64bec32001-09-18 02:26:39 +0000721
Martin v. Löwis44f86962001-09-05 13:44:54 +0000722 def run(self):
723 self.finished.wait(self.interval)
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000724 if not self.finished.is_set():
Martin v. Löwis44f86962001-09-05 13:44:54 +0000725 self.function(*self.args, **self.kwargs)
726 self.finished.set()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000727
728# Special thread class to represent the main thread
729# This is garbage collected through an exit handler
730
731class _MainThread(Thread):
732
733 def __init__(self):
734 Thread.__init__(self, name="MainThread")
Jeffrey Yasskin69e13092008-02-28 06:09:19 +0000735 self._Thread__started.set()
Benjamin Petersonbd9dd312009-03-31 21:06:30 +0000736 with _active_limbo_lock:
737 _active[_get_ident()] = self
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000738
739 def _set_daemon(self):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000740 return False
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000741
Martin v. Löwis7b7c9d42007-01-04 21:06:12 +0000742 def _exitfunc(self):
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000743 self._Thread__stop()
744 t = _pickSomeNonDaemonThread()
745 if t:
746 if __debug__:
747 self._note("%s: waiting for other threads", self)
748 while t:
749 t.join()
750 t = _pickSomeNonDaemonThread()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000751 if __debug__:
752 self._note("%s: exiting", self)
753 self._Thread__delete()
754
755def _pickSomeNonDaemonThread():
756 for t in enumerate():
Benjamin Petersoncbae8692008-08-18 17:45:09 +0000757 if not t.daemon and t.is_alive():
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000758 return t
759 return None
760
761
762# Dummy thread class to represent threads not started here.
Tim Peters711906e2005-01-08 07:30:42 +0000763# These aren't garbage collected when they die, nor can they be waited for.
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000764# If they invoke anything in threading.py that calls current_thread(), they
Tim Peters711906e2005-01-08 07:30:42 +0000765# leave an entry in the _active dict forever after.
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000766# Their purpose is to return *something* from current_thread().
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000767# They are marked as daemon threads so we won't wait for them
768# when we exit (conform previous semantics).
769
770class _DummyThread(Thread):
Tim Petersb90f89a2001-01-15 03:26:36 +0000771
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000772 def __init__(self):
773 Thread.__init__(self, name=_newname("Dummy-%d"))
Tim Peters711906e2005-01-08 07:30:42 +0000774
775 # Thread.__block consumes an OS-level locking primitive, which
776 # can never be used by a _DummyThread. Since a _DummyThread
777 # instance is immortal, that's bad, so release this resource.
Brett Cannone6539c42005-01-08 02:43:53 +0000778 del self._Thread__block
Tim Peters711906e2005-01-08 07:30:42 +0000779
Jeffrey Yasskin69e13092008-02-28 06:09:19 +0000780 self._Thread__started.set()
Benjamin Petersonbd9dd312009-03-31 21:06:30 +0000781 with _active_limbo_lock:
782 _active[_get_ident()] = self
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000783
784 def _set_daemon(self):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000785 return True
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000786
Neal Norwitz45bec8c2002-02-19 03:01:36 +0000787 def join(self, timeout=None):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000788 assert False, "cannot join a dummy thread"
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000789
790
791# Global API functions
792
Benjamin Peterson973e6c22008-09-01 23:12:58 +0000793def currentThread():
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000794 try:
795 return _active[_get_ident()]
796 except KeyError:
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000797 ##print "current_thread(): no current thread for", _get_ident()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000798 return _DummyThread()
799
Benjamin Peterson973e6c22008-09-01 23:12:58 +0000800current_thread = currentThread
Benjamin Petersonf4395602008-06-11 17:50:00 +0000801
Benjamin Peterson973e6c22008-09-01 23:12:58 +0000802def activeCount():
Benjamin Petersonbd9dd312009-03-31 21:06:30 +0000803 with _active_limbo_lock:
804 return len(_active) + len(_limbo)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000805
Benjamin Peterson973e6c22008-09-01 23:12:58 +0000806active_count = activeCount
Benjamin Petersonf4395602008-06-11 17:50:00 +0000807
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000808def enumerate():
Benjamin Petersonbd9dd312009-03-31 21:06:30 +0000809 with _active_limbo_lock:
810 return _active.values() + _limbo.values()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000811
Andrew MacIntyre92913322006-06-13 15:04:24 +0000812from thread import stack_size
813
Martin v. Löwis7b7c9d42007-01-04 21:06:12 +0000814# Create the main thread object,
815# and make it available for the interpreter
816# (Py_Main) as threading._shutdown.
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000817
Martin v. Löwis7b7c9d42007-01-04 21:06:12 +0000818_shutdown = _MainThread()._exitfunc
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000819
Jim Fultond15dc062004-07-14 19:11:50 +0000820# get thread-local implementation, either from the thread
821# module, or from the python fallback
822
823try:
824 from thread import _local as local
825except ImportError:
826 from _threading_local import local
827
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000828
Jesse Noller5e62ca42008-07-16 20:03:47 +0000829def _after_fork():
830 # This function is called by Python/ceval.c:PyEval_ReInitThreads which
831 # is called from PyOS_AfterFork. Here we cleanup threading module state
832 # that should not exist after a fork.
833
834 # Reset _active_limbo_lock, in case we forked while the lock was held
835 # by another (non-forked) thread. http://bugs.python.org/issue874900
836 global _active_limbo_lock
837 _active_limbo_lock = _allocate_lock()
838
839 # fork() only copied the current thread; clear references to others.
840 new_active = {}
841 current = current_thread()
842 with _active_limbo_lock:
Antoine Pitrou9fb1aca2008-09-06 23:04:32 +0000843 for thread in _active.itervalues():
Jesse Noller5e62ca42008-07-16 20:03:47 +0000844 if thread is current:
Antoine Pitrou9fb1aca2008-09-06 23:04:32 +0000845 # There is only one active thread. We reset the ident to
846 # its new value since it can have changed.
847 ident = _get_ident()
848 thread._Thread__ident = ident
Jesse Noller5e62ca42008-07-16 20:03:47 +0000849 new_active[ident] = thread
850 else:
851 # All the others are already stopped.
852 # We don't call _Thread__stop() because it tries to acquire
853 # thread._Thread__block which could also have been held while
854 # we forked.
855 thread._Thread__stopped = True
856
857 _limbo.clear()
858 _active.clear()
859 _active.update(new_active)
860 assert len(_active) == 1
861
862
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000863# Self-test code
864
865def _test():
866
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000867 class BoundedQueue(_Verbose):
868
869 def __init__(self, limit):
870 _Verbose.__init__(self)
871 self.mon = RLock()
872 self.rc = Condition(self.mon)
873 self.wc = Condition(self.mon)
874 self.limit = limit
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000875 self.queue = deque()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000876
877 def put(self, item):
878 self.mon.acquire()
879 while len(self.queue) >= self.limit:
880 self._note("put(%s): queue full", item)
881 self.wc.wait()
882 self.queue.append(item)
883 self._note("put(%s): appended, length now %d",
884 item, len(self.queue))
885 self.rc.notify()
886 self.mon.release()
887
888 def get(self):
889 self.mon.acquire()
890 while not self.queue:
891 self._note("get(): queue empty")
892 self.rc.wait()
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000893 item = self.queue.popleft()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000894 self._note("get(): got %s, %d left", item, len(self.queue))
895 self.wc.notify()
896 self.mon.release()
897 return item
898
899 class ProducerThread(Thread):
900
901 def __init__(self, queue, quota):
902 Thread.__init__(self, name="Producer")
903 self.queue = queue
904 self.quota = quota
905
906 def run(self):
Guido van Rossumb26a1b41998-05-20 17:05:52 +0000907 from random import random
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000908 counter = 0
909 while counter < self.quota:
910 counter = counter + 1
Benjamin Petersoncbae8692008-08-18 17:45:09 +0000911 self.queue.put("%s.%d" % (self.name, counter))
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000912 _sleep(random() * 0.00001)
913
914
915 class ConsumerThread(Thread):
916
917 def __init__(self, queue, count):
918 Thread.__init__(self, name="Consumer")
919 self.queue = queue
920 self.count = count
921
922 def run(self):
923 while self.count > 0:
924 item = self.queue.get()
925 print item
926 self.count = self.count - 1
927
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000928 NP = 3
929 QL = 4
930 NI = 5
931
932 Q = BoundedQueue(QL)
933 P = []
934 for i in range(NP):
935 t = ProducerThread(Q, NI)
Benjamin Petersoncbae8692008-08-18 17:45:09 +0000936 t.name = ("Producer-%d" % (i+1))
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000937 P.append(t)
938 C = ConsumerThread(Q, NI*NP)
939 for t in P:
940 t.start()
941 _sleep(0.000001)
942 C.start()
943 for t in P:
944 t.join()
945 C.join()
946
947if __name__ == '__main__':
948 _test()