blob: 74e93bb175c2285c330af4145008ca4dca05d0a7 [file] [log] [blame]
Guido van Rossume7b146f2000-02-04 15:28:42 +00001"""Proposed new threading module, emulating a subset of Java's threading model."""
Guido van Rossum7f5013a1998-04-09 22:01:42 +00002
3import sys
4import time
5import thread
6import traceback
7import StringIO
8
9# Rename some stuff so "from threading import *" is safe
10
11_sys = sys
12del sys
13
14_time = time.time
15_sleep = time.sleep
16del time
17
18_start_new_thread = thread.start_new_thread
19_allocate_lock = thread.allocate_lock
20_get_ident = thread.get_ident
Jeremy Hyltonb5fc7492000-06-01 01:17:17 +000021ThreadError = thread.error
Guido van Rossum7f5013a1998-04-09 22:01:42 +000022del thread
23
24_print_exc = traceback.print_exc
25del traceback
26
27_StringIO = StringIO.StringIO
28del StringIO
29
30
31# Debug support (adapted from ihooks.py)
32
33_VERBOSE = 0
34
35if __debug__:
36
37 class _Verbose:
38
39 def __init__(self, verbose=None):
40 if verbose is None:
41 verbose = _VERBOSE
42 self.__verbose = verbose
43
44 def _note(self, format, *args):
45 if self.__verbose:
46 format = format % args
47 format = "%s: %s\n" % (
48 currentThread().getName(), format)
49 _sys.stderr.write(format)
50
51else:
52 # Disable this when using "python -O"
53 class _Verbose:
54 def __init__(self, verbose=None):
55 pass
56 def _note(self, *args):
57 pass
58
59
60# Synchronization classes
61
62Lock = _allocate_lock
63
64def RLock(*args, **kwargs):
65 return apply(_RLock, args, kwargs)
66
67class _RLock(_Verbose):
Tim Petersb90f89a2001-01-15 03:26:36 +000068
Guido van Rossum7f5013a1998-04-09 22:01:42 +000069 def __init__(self, verbose=None):
70 _Verbose.__init__(self, verbose)
71 self.__block = _allocate_lock()
72 self.__owner = None
73 self.__count = 0
74
75 def __repr__(self):
76 return "<%s(%s, %d)>" % (
77 self.__class__.__name__,
78 self.__owner and self.__owner.getName(),
79 self.__count)
80
81 def acquire(self, blocking=1):
82 me = currentThread()
83 if self.__owner is me:
84 self.__count = self.__count + 1
85 if __debug__:
86 self._note("%s.acquire(%s): recursive success", self, blocking)
87 return 1
88 rc = self.__block.acquire(blocking)
89 if rc:
90 self.__owner = me
91 self.__count = 1
92 if __debug__:
93 self._note("%s.acquire(%s): initial succes", self, blocking)
94 else:
95 if __debug__:
96 self._note("%s.acquire(%s): failure", self, blocking)
97 return rc
98
99 def release(self):
100 me = currentThread()
101 assert self.__owner is me, "release() of un-acquire()d lock"
102 self.__count = count = self.__count - 1
103 if not count:
104 self.__owner = None
105 self.__block.release()
106 if __debug__:
107 self._note("%s.release(): final release", self)
108 else:
109 if __debug__:
110 self._note("%s.release(): non-final release", self)
111
112 # Internal methods used by condition variables
113
114 def _acquire_restore(self, (count, owner)):
115 self.__block.acquire()
116 self.__count = count
117 self.__owner = owner
118 if __debug__:
119 self._note("%s._acquire_restore()", self)
120
121 def _release_save(self):
122 if __debug__:
123 self._note("%s._release_save()", self)
124 count = self.__count
125 self.__count = 0
126 owner = self.__owner
127 self.__owner = None
128 self.__block.release()
129 return (count, owner)
130
131 def _is_owned(self):
132 return self.__owner is currentThread()
133
134
135def Condition(*args, **kwargs):
136 return apply(_Condition, args, kwargs)
137
138class _Condition(_Verbose):
139
140 def __init__(self, lock=None, verbose=None):
141 _Verbose.__init__(self, verbose)
142 if lock is None:
143 lock = RLock()
144 self.__lock = lock
145 # Export the lock's acquire() and release() methods
146 self.acquire = lock.acquire
147 self.release = lock.release
148 # If the lock defines _release_save() and/or _acquire_restore(),
149 # these override the default implementations (which just call
150 # release() and acquire() on the lock). Ditto for _is_owned().
151 try:
152 self._release_save = lock._release_save
153 except AttributeError:
154 pass
155 try:
156 self._acquire_restore = lock._acquire_restore
157 except AttributeError:
158 pass
159 try:
160 self._is_owned = lock._is_owned
161 except AttributeError:
162 pass
163 self.__waiters = []
164
165 def __repr__(self):
166 return "<Condition(%s, %d)>" % (self.__lock, len(self.__waiters))
167
168 def _release_save(self):
169 self.__lock.release() # No state to save
170
171 def _acquire_restore(self, x):
172 self.__lock.acquire() # Ignore saved state
173
174 def _is_owned(self):
175 if self.__lock.acquire(0):
176 self.__lock.release()
177 return 0
178 else:
179 return 1
180
181 def wait(self, timeout=None):
182 me = currentThread()
183 assert self._is_owned(), "wait() of un-acquire()d lock"
184 waiter = _allocate_lock()
185 waiter.acquire()
186 self.__waiters.append(waiter)
187 saved_state = self._release_save()
Tim Petersc951bf92001-04-02 20:15:57 +0000188 try: # restore state no matter what (e.g., KeyboardInterrupt)
189 if timeout is None:
190 waiter.acquire()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000191 if __debug__:
Tim Petersc951bf92001-04-02 20:15:57 +0000192 self._note("%s.wait(): got it", self)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000193 else:
Tim Petersa6a4f272001-08-12 00:41:33 +0000194 # Balancing act: We can't afford a pure busy loop, so we
195 # have to sleep; but if we sleep the whole timeout time,
196 # we'll be unresponsive. The scheme here sleeps very
197 # little at first, longer as time goes on, but never longer
198 # than 20 times per second (or the timeout time remaining).
Tim Petersc951bf92001-04-02 20:15:57 +0000199 endtime = _time() + timeout
Tim Petersa6a4f272001-08-12 00:41:33 +0000200 delay = 0.0005 # 500 us -> initial delay of 1 ms
Tim Petersc951bf92001-04-02 20:15:57 +0000201 while 1:
202 gotit = waiter.acquire(0)
Tim Petersa6a4f272001-08-12 00:41:33 +0000203 if gotit:
Tim Petersc951bf92001-04-02 20:15:57 +0000204 break
Tim Petersa6a4f272001-08-12 00:41:33 +0000205 remaining = endtime - _time()
206 if remaining <= 0:
207 break
208 delay = min(delay * 2, remaining, .05)
Tim Petersc951bf92001-04-02 20:15:57 +0000209 _sleep(delay)
Tim Petersc951bf92001-04-02 20:15:57 +0000210 if not gotit:
211 if __debug__:
212 self._note("%s.wait(%s): timed out", self, timeout)
213 try:
214 self.__waiters.remove(waiter)
215 except ValueError:
216 pass
217 else:
218 if __debug__:
219 self._note("%s.wait(%s): got it", self, timeout)
220 finally:
221 self._acquire_restore(saved_state)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000222
223 def notify(self, n=1):
224 me = currentThread()
225 assert self._is_owned(), "notify() of un-acquire()d lock"
226 __waiters = self.__waiters
227 waiters = __waiters[:n]
228 if not waiters:
229 if __debug__:
230 self._note("%s.notify(): no waiters", self)
231 return
232 self._note("%s.notify(): notifying %d waiter%s", self, n,
233 n!=1 and "s" or "")
234 for waiter in waiters:
235 waiter.release()
236 try:
237 __waiters.remove(waiter)
238 except ValueError:
239 pass
240
241 def notifyAll(self):
242 self.notify(len(self.__waiters))
243
244
245def Semaphore(*args, **kwargs):
246 return apply(_Semaphore, args, kwargs)
247
248class _Semaphore(_Verbose):
249
Andrew M. Kuchling39d3bfc2000-02-29 00:10:24 +0000250 # After Tim Peters' semaphore class, but not quite the same (no maximum)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000251
252 def __init__(self, value=1, verbose=None):
253 assert value >= 0, "Semaphore initial value must be >= 0"
254 _Verbose.__init__(self, verbose)
255 self.__cond = Condition(Lock())
256 self.__value = value
257
258 def acquire(self, blocking=1):
259 rc = 0
260 self.__cond.acquire()
261 while self.__value == 0:
262 if not blocking:
263 break
264 self.__cond.wait()
265 else:
266 self.__value = self.__value - 1
267 rc = 1
268 self.__cond.release()
269 return rc
270
271 def release(self):
272 self.__cond.acquire()
273 self.__value = self.__value + 1
274 self.__cond.notify()
275 self.__cond.release()
276
277
278def Event(*args, **kwargs):
279 return apply(_Event, args, kwargs)
280
281class _Event(_Verbose):
282
283 # After Tim Peters' event class (without is_posted())
284
285 def __init__(self, verbose=None):
286 _Verbose.__init__(self, verbose)
287 self.__cond = Condition(Lock())
288 self.__flag = 0
289
290 def isSet(self):
291 return self.__flag
292
293 def set(self):
294 self.__cond.acquire()
295 self.__flag = 1
296 self.__cond.notifyAll()
297 self.__cond.release()
298
299 def clear(self):
300 self.__cond.acquire()
301 self.__flag = 0
302 self.__cond.release()
303
304 def wait(self, timeout=None):
305 self.__cond.acquire()
306 if not self.__flag:
307 self.__cond.wait(timeout)
308 self.__cond.release()
309
310
311# Helper to generate new thread names
312_counter = 0
313def _newname(template="Thread-%d"):
314 global _counter
315 _counter = _counter + 1
316 return template % _counter
317
318# Active thread administration
319_active_limbo_lock = _allocate_lock()
320_active = {}
321_limbo = {}
322
323
324# Main class for threads
325
326class Thread(_Verbose):
327
328 __initialized = 0
329
330 def __init__(self, group=None, target=None, name=None,
331 args=(), kwargs={}, verbose=None):
Guido van Rossum5a43e1a1998-06-09 19:04:26 +0000332 assert group is None, "group argument must be None for now"
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000333 _Verbose.__init__(self, verbose)
334 self.__target = target
335 self.__name = str(name or _newname())
336 self.__args = args
337 self.__kwargs = kwargs
338 self.__daemonic = self._set_daemon()
339 self.__started = 0
340 self.__stopped = 0
341 self.__block = Condition(Lock())
342 self.__initialized = 1
343
344 def _set_daemon(self):
345 # Overridden in _MainThread and _DummyThread
346 return currentThread().isDaemon()
347
348 def __repr__(self):
349 assert self.__initialized, "Thread.__init__() was not called"
350 status = "initial"
351 if self.__started:
352 status = "started"
353 if self.__stopped:
354 status = "stopped"
355 if self.__daemonic:
356 status = status + " daemon"
357 return "<%s(%s, %s)>" % (self.__class__.__name__, self.__name, status)
358
359 def start(self):
360 assert self.__initialized, "Thread.__init__() not called"
361 assert not self.__started, "thread already started"
362 if __debug__:
363 self._note("%s.start(): starting thread", self)
364 _active_limbo_lock.acquire()
365 _limbo[self] = self
366 _active_limbo_lock.release()
367 _start_new_thread(self.__bootstrap, ())
368 self.__started = 1
369 _sleep(0.000001) # 1 usec, to let the thread run (Solaris hack)
370
371 def run(self):
372 if self.__target:
373 apply(self.__target, self.__args, self.__kwargs)
374
375 def __bootstrap(self):
376 try:
377 self.__started = 1
378 _active_limbo_lock.acquire()
379 _active[_get_ident()] = self
380 del _limbo[self]
381 _active_limbo_lock.release()
382 if __debug__:
383 self._note("%s.__bootstrap(): thread started", self)
384 try:
385 self.run()
386 except SystemExit:
387 if __debug__:
388 self._note("%s.__bootstrap(): raised SystemExit", self)
389 except:
390 if __debug__:
391 self._note("%s.__bootstrap(): unhandled exception", self)
392 s = _StringIO()
393 _print_exc(file=s)
394 _sys.stderr.write("Exception in thread %s:\n%s\n" %
395 (self.getName(), s.getvalue()))
396 else:
397 if __debug__:
398 self._note("%s.__bootstrap(): normal return", self)
399 finally:
400 self.__stop()
401 self.__delete()
402
403 def __stop(self):
404 self.__block.acquire()
405 self.__stopped = 1
406 self.__block.notifyAll()
407 self.__block.release()
408
409 def __delete(self):
410 _active_limbo_lock.acquire()
411 del _active[_get_ident()]
412 _active_limbo_lock.release()
413
414 def join(self, timeout=None):
415 assert self.__initialized, "Thread.__init__() not called"
Guido van Rossum5a43e1a1998-06-09 19:04:26 +0000416 assert self.__started, "cannot join thread before it is started"
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000417 assert self is not currentThread(), "cannot join current thread"
418 if __debug__:
419 if not self.__stopped:
420 self._note("%s.join(): waiting until thread stops", self)
421 self.__block.acquire()
422 if timeout is None:
Guido van Rossum5a43e1a1998-06-09 19:04:26 +0000423 while not self.__stopped:
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000424 self.__block.wait()
425 if __debug__:
426 self._note("%s.join(): thread stopped", self)
427 else:
Guido van Rossumb39e4611998-05-29 17:47:10 +0000428 deadline = _time() + timeout
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000429 while not self.__stopped:
Guido van Rossumb39e4611998-05-29 17:47:10 +0000430 delay = deadline - _time()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000431 if delay <= 0:
432 if __debug__:
433 self._note("%s.join(): timed out", self)
434 break
435 self.__block.wait(delay)
436 else:
437 if __debug__:
438 self._note("%s.join(): thread stopped", self)
439 self.__block.release()
440
441 def getName(self):
442 assert self.__initialized, "Thread.__init__() not called"
443 return self.__name
444
445 def setName(self, name):
446 assert self.__initialized, "Thread.__init__() not called"
447 self.__name = str(name)
448
449 def isAlive(self):
450 assert self.__initialized, "Thread.__init__() not called"
451 return self.__started and not self.__stopped
Tim Petersb90f89a2001-01-15 03:26:36 +0000452
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000453 def isDaemon(self):
454 assert self.__initialized, "Thread.__init__() not called"
455 return self.__daemonic
456
457 def setDaemon(self, daemonic):
458 assert self.__initialized, "Thread.__init__() not called"
459 assert not self.__started, "cannot set daemon status of active thread"
460 self.__daemonic = daemonic
461
462
463# Special thread class to represent the main thread
464# This is garbage collected through an exit handler
465
466class _MainThread(Thread):
467
468 def __init__(self):
469 Thread.__init__(self, name="MainThread")
470 self._Thread__started = 1
471 _active_limbo_lock.acquire()
472 _active[_get_ident()] = self
473 _active_limbo_lock.release()
Fred Drake7b4fc172000-08-18 15:50:54 +0000474 import atexit
475 atexit.register(self.__exitfunc)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000476
477 def _set_daemon(self):
478 return 0
479
480 def __exitfunc(self):
481 self._Thread__stop()
482 t = _pickSomeNonDaemonThread()
483 if t:
484 if __debug__:
485 self._note("%s: waiting for other threads", self)
486 while t:
487 t.join()
488 t = _pickSomeNonDaemonThread()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000489 if __debug__:
490 self._note("%s: exiting", self)
491 self._Thread__delete()
492
493def _pickSomeNonDaemonThread():
494 for t in enumerate():
495 if not t.isDaemon() and t.isAlive():
496 return t
497 return None
498
499
500# Dummy thread class to represent threads not started here.
501# These aren't garbage collected when they die,
502# nor can they be waited for.
503# Their purpose is to return *something* from currentThread().
504# They are marked as daemon threads so we won't wait for them
505# when we exit (conform previous semantics).
506
507class _DummyThread(Thread):
Tim Petersb90f89a2001-01-15 03:26:36 +0000508
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000509 def __init__(self):
510 Thread.__init__(self, name=_newname("Dummy-%d"))
Guido van Rossum8e7eaa81999-09-29 15:26:52 +0000511 self._Thread__started = 1
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000512 _active_limbo_lock.acquire()
513 _active[_get_ident()] = self
514 _active_limbo_lock.release()
515
516 def _set_daemon(self):
517 return 1
518
519 def join(self):
520 assert 0, "cannot join a dummy thread"
521
522
523# Global API functions
524
525def currentThread():
526 try:
527 return _active[_get_ident()]
528 except KeyError:
Guido van Rossum5080b332000-12-15 20:08:39 +0000529 ##print "currentThread(): no current thread for", _get_ident()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000530 return _DummyThread()
531
532def activeCount():
533 _active_limbo_lock.acquire()
534 count = len(_active) + len(_limbo)
535 _active_limbo_lock.release()
536 return count
537
538def enumerate():
539 _active_limbo_lock.acquire()
540 active = _active.values() + _limbo.values()
541 _active_limbo_lock.release()
542 return active
543
544
545# Create the main thread object
546
547_MainThread()
548
549
550# Self-test code
551
552def _test():
553
Guido van Rossumb26a1b41998-05-20 17:05:52 +0000554 import random
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000555
556 class BoundedQueue(_Verbose):
557
558 def __init__(self, limit):
559 _Verbose.__init__(self)
560 self.mon = RLock()
561 self.rc = Condition(self.mon)
562 self.wc = Condition(self.mon)
563 self.limit = limit
564 self.queue = []
565
566 def put(self, item):
567 self.mon.acquire()
568 while len(self.queue) >= self.limit:
569 self._note("put(%s): queue full", item)
570 self.wc.wait()
571 self.queue.append(item)
572 self._note("put(%s): appended, length now %d",
573 item, len(self.queue))
574 self.rc.notify()
575 self.mon.release()
576
577 def get(self):
578 self.mon.acquire()
579 while not self.queue:
580 self._note("get(): queue empty")
581 self.rc.wait()
582 item = self.queue[0]
583 del self.queue[0]
584 self._note("get(): got %s, %d left", item, len(self.queue))
585 self.wc.notify()
586 self.mon.release()
587 return item
588
589 class ProducerThread(Thread):
590
591 def __init__(self, queue, quota):
592 Thread.__init__(self, name="Producer")
593 self.queue = queue
594 self.quota = quota
595
596 def run(self):
Guido van Rossumb26a1b41998-05-20 17:05:52 +0000597 from random import random
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000598 counter = 0
599 while counter < self.quota:
600 counter = counter + 1
601 self.queue.put("%s.%d" % (self.getName(), counter))
602 _sleep(random() * 0.00001)
603
604
605 class ConsumerThread(Thread):
606
607 def __init__(self, queue, count):
608 Thread.__init__(self, name="Consumer")
609 self.queue = queue
610 self.count = count
611
612 def run(self):
613 while self.count > 0:
614 item = self.queue.get()
615 print item
616 self.count = self.count - 1
617
618 import time
619
620 NP = 3
621 QL = 4
622 NI = 5
623
624 Q = BoundedQueue(QL)
625 P = []
626 for i in range(NP):
627 t = ProducerThread(Q, NI)
628 t.setName("Producer-%d" % (i+1))
629 P.append(t)
630 C = ConsumerThread(Q, NI*NP)
631 for t in P:
632 t.start()
633 _sleep(0.000001)
634 C.start()
635 for t in P:
636 t.join()
637 C.join()
638
639if __name__ == '__main__':
640 _test()