blob: fbf40cd04c6732103060987ae72aaac3f5625a57 [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
Skip Montanarob446fc72001-08-19 04:25:24 +0000264 if __debug__:
265 self._note("%s.acquire(%s): blocked waiting, value=%s",
266 self, blocking, self.__value)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000267 self.__cond.wait()
268 else:
269 self.__value = self.__value - 1
Skip Montanarob446fc72001-08-19 04:25:24 +0000270 if __debug__:
Skip Montanaroae8454a2001-08-19 05:53:47 +0000271 self._note("%s.acquire: success, value=%s",
272 self, self.__value)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000273 rc = 1
274 self.__cond.release()
275 return rc
276
277 def release(self):
278 self.__cond.acquire()
279 self.__value = self.__value + 1
Skip Montanarob446fc72001-08-19 04:25:24 +0000280 if __debug__:
Skip Montanaroae8454a2001-08-19 05:53:47 +0000281 self._note("%s.release: success, value=%s",
282 self, self.__value)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000283 self.__cond.notify()
284 self.__cond.release()
285
286
Skip Montanaroe428bb72001-08-20 20:27:58 +0000287def BoundedSemaphore(*args, **kwargs):
288 return apply(_BoundedSemaphore, args, kwargs)
289
290class _BoundedSemaphore(_Semaphore):
291 """Semaphore that checks that # releases is <= # acquires"""
292 def __init__(self, value=1, verbose=None):
293 _Semaphore.__init__(self, value, verbose)
294 self._initial_value = value
295
296 def release(self):
297 if self._Semaphore__value >= self._initial_value:
298 raise ValueError, "Semaphore released too many times"
299 return _Semaphore.release(self)
300
301
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000302def Event(*args, **kwargs):
303 return apply(_Event, args, kwargs)
304
305class _Event(_Verbose):
306
307 # After Tim Peters' event class (without is_posted())
308
309 def __init__(self, verbose=None):
310 _Verbose.__init__(self, verbose)
311 self.__cond = Condition(Lock())
312 self.__flag = 0
313
314 def isSet(self):
315 return self.__flag
316
317 def set(self):
318 self.__cond.acquire()
319 self.__flag = 1
320 self.__cond.notifyAll()
321 self.__cond.release()
322
323 def clear(self):
324 self.__cond.acquire()
325 self.__flag = 0
326 self.__cond.release()
327
328 def wait(self, timeout=None):
329 self.__cond.acquire()
330 if not self.__flag:
331 self.__cond.wait(timeout)
332 self.__cond.release()
333
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000334# Helper to generate new thread names
335_counter = 0
336def _newname(template="Thread-%d"):
337 global _counter
338 _counter = _counter + 1
339 return template % _counter
340
341# Active thread administration
342_active_limbo_lock = _allocate_lock()
343_active = {}
344_limbo = {}
345
346
347# Main class for threads
348
349class Thread(_Verbose):
350
351 __initialized = 0
352
353 def __init__(self, group=None, target=None, name=None,
354 args=(), kwargs={}, verbose=None):
Guido van Rossum5a43e1a1998-06-09 19:04:26 +0000355 assert group is None, "group argument must be None for now"
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000356 _Verbose.__init__(self, verbose)
357 self.__target = target
358 self.__name = str(name or _newname())
359 self.__args = args
360 self.__kwargs = kwargs
361 self.__daemonic = self._set_daemon()
362 self.__started = 0
363 self.__stopped = 0
364 self.__block = Condition(Lock())
365 self.__initialized = 1
366
367 def _set_daemon(self):
368 # Overridden in _MainThread and _DummyThread
369 return currentThread().isDaemon()
370
371 def __repr__(self):
372 assert self.__initialized, "Thread.__init__() was not called"
373 status = "initial"
374 if self.__started:
375 status = "started"
376 if self.__stopped:
377 status = "stopped"
378 if self.__daemonic:
379 status = status + " daemon"
380 return "<%s(%s, %s)>" % (self.__class__.__name__, self.__name, status)
381
382 def start(self):
383 assert self.__initialized, "Thread.__init__() not called"
384 assert not self.__started, "thread already started"
385 if __debug__:
386 self._note("%s.start(): starting thread", self)
387 _active_limbo_lock.acquire()
388 _limbo[self] = self
389 _active_limbo_lock.release()
390 _start_new_thread(self.__bootstrap, ())
391 self.__started = 1
392 _sleep(0.000001) # 1 usec, to let the thread run (Solaris hack)
393
394 def run(self):
395 if self.__target:
396 apply(self.__target, self.__args, self.__kwargs)
397
398 def __bootstrap(self):
399 try:
400 self.__started = 1
401 _active_limbo_lock.acquire()
402 _active[_get_ident()] = self
403 del _limbo[self]
404 _active_limbo_lock.release()
405 if __debug__:
406 self._note("%s.__bootstrap(): thread started", self)
407 try:
408 self.run()
409 except SystemExit:
410 if __debug__:
411 self._note("%s.__bootstrap(): raised SystemExit", self)
412 except:
413 if __debug__:
414 self._note("%s.__bootstrap(): unhandled exception", self)
415 s = _StringIO()
416 _print_exc(file=s)
417 _sys.stderr.write("Exception in thread %s:\n%s\n" %
418 (self.getName(), s.getvalue()))
419 else:
420 if __debug__:
421 self._note("%s.__bootstrap(): normal return", self)
422 finally:
423 self.__stop()
424 self.__delete()
425
426 def __stop(self):
427 self.__block.acquire()
428 self.__stopped = 1
429 self.__block.notifyAll()
430 self.__block.release()
431
432 def __delete(self):
433 _active_limbo_lock.acquire()
434 del _active[_get_ident()]
435 _active_limbo_lock.release()
436
437 def join(self, timeout=None):
438 assert self.__initialized, "Thread.__init__() not called"
Guido van Rossum5a43e1a1998-06-09 19:04:26 +0000439 assert self.__started, "cannot join thread before it is started"
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000440 assert self is not currentThread(), "cannot join current thread"
441 if __debug__:
442 if not self.__stopped:
443 self._note("%s.join(): waiting until thread stops", self)
444 self.__block.acquire()
445 if timeout is None:
Guido van Rossum5a43e1a1998-06-09 19:04:26 +0000446 while not self.__stopped:
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000447 self.__block.wait()
448 if __debug__:
449 self._note("%s.join(): thread stopped", self)
450 else:
Guido van Rossumb39e4611998-05-29 17:47:10 +0000451 deadline = _time() + timeout
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000452 while not self.__stopped:
Guido van Rossumb39e4611998-05-29 17:47:10 +0000453 delay = deadline - _time()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000454 if delay <= 0:
455 if __debug__:
456 self._note("%s.join(): timed out", self)
457 break
458 self.__block.wait(delay)
459 else:
460 if __debug__:
461 self._note("%s.join(): thread stopped", self)
462 self.__block.release()
463
464 def getName(self):
465 assert self.__initialized, "Thread.__init__() not called"
466 return self.__name
467
468 def setName(self, name):
469 assert self.__initialized, "Thread.__init__() not called"
470 self.__name = str(name)
471
472 def isAlive(self):
473 assert self.__initialized, "Thread.__init__() not called"
474 return self.__started and not self.__stopped
Tim Petersb90f89a2001-01-15 03:26:36 +0000475
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000476 def isDaemon(self):
477 assert self.__initialized, "Thread.__init__() not called"
478 return self.__daemonic
479
480 def setDaemon(self, daemonic):
481 assert self.__initialized, "Thread.__init__() not called"
482 assert not self.__started, "cannot set daemon status of active thread"
483 self.__daemonic = daemonic
484
Martin v. Löwis44f86962001-09-05 13:44:54 +0000485# The timer class was contributed by Itamar Shtull-Trauring
486
487def Timer(*args, **kwargs):
488 return _Timer(*args, **kwargs)
489
490class _Timer(Thread):
491 """Call a function after a specified number of seconds:
Tim Petersb64bec32001-09-18 02:26:39 +0000492
Martin v. Löwis44f86962001-09-05 13:44:54 +0000493 t = Timer(30.0, f, args=[], kwargs={})
494 t.start()
495 t.cancel() # stop the timer's action if it's still waiting
496 """
Tim Petersb64bec32001-09-18 02:26:39 +0000497
Martin v. Löwis44f86962001-09-05 13:44:54 +0000498 def __init__(self, interval, function, args=[], kwargs={}):
499 Thread.__init__(self)
500 self.interval = interval
501 self.function = function
502 self.args = args
503 self.kwargs = kwargs
504 self.finished = Event()
Tim Petersb64bec32001-09-18 02:26:39 +0000505
Martin v. Löwis44f86962001-09-05 13:44:54 +0000506 def cancel(self):
507 """Stop the timer if it hasn't finished yet"""
508 self.finished.set()
Tim Petersb64bec32001-09-18 02:26:39 +0000509
Martin v. Löwis44f86962001-09-05 13:44:54 +0000510 def run(self):
511 self.finished.wait(self.interval)
512 if not self.finished.isSet():
513 self.function(*self.args, **self.kwargs)
514 self.finished.set()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000515
516# Special thread class to represent the main thread
517# This is garbage collected through an exit handler
518
519class _MainThread(Thread):
520
521 def __init__(self):
522 Thread.__init__(self, name="MainThread")
523 self._Thread__started = 1
524 _active_limbo_lock.acquire()
525 _active[_get_ident()] = self
526 _active_limbo_lock.release()
Fred Drake7b4fc172000-08-18 15:50:54 +0000527 import atexit
528 atexit.register(self.__exitfunc)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000529
530 def _set_daemon(self):
531 return 0
532
533 def __exitfunc(self):
534 self._Thread__stop()
535 t = _pickSomeNonDaemonThread()
536 if t:
537 if __debug__:
538 self._note("%s: waiting for other threads", self)
539 while t:
540 t.join()
541 t = _pickSomeNonDaemonThread()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000542 if __debug__:
543 self._note("%s: exiting", self)
544 self._Thread__delete()
545
546def _pickSomeNonDaemonThread():
547 for t in enumerate():
548 if not t.isDaemon() and t.isAlive():
549 return t
550 return None
551
552
553# Dummy thread class to represent threads not started here.
554# These aren't garbage collected when they die,
555# nor can they be waited for.
556# Their purpose is to return *something* from currentThread().
557# They are marked as daemon threads so we won't wait for them
558# when we exit (conform previous semantics).
559
560class _DummyThread(Thread):
Tim Petersb90f89a2001-01-15 03:26:36 +0000561
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000562 def __init__(self):
563 Thread.__init__(self, name=_newname("Dummy-%d"))
Guido van Rossum8e7eaa81999-09-29 15:26:52 +0000564 self._Thread__started = 1
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000565 _active_limbo_lock.acquire()
566 _active[_get_ident()] = self
567 _active_limbo_lock.release()
568
569 def _set_daemon(self):
570 return 1
571
572 def join(self):
573 assert 0, "cannot join a dummy thread"
574
575
576# Global API functions
577
578def currentThread():
579 try:
580 return _active[_get_ident()]
581 except KeyError:
Guido van Rossum5080b332000-12-15 20:08:39 +0000582 ##print "currentThread(): no current thread for", _get_ident()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000583 return _DummyThread()
584
585def activeCount():
586 _active_limbo_lock.acquire()
587 count = len(_active) + len(_limbo)
588 _active_limbo_lock.release()
589 return count
590
591def enumerate():
592 _active_limbo_lock.acquire()
593 active = _active.values() + _limbo.values()
594 _active_limbo_lock.release()
595 return active
596
597
598# Create the main thread object
599
600_MainThread()
601
602
603# Self-test code
604
605def _test():
606
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000607 class BoundedQueue(_Verbose):
608
609 def __init__(self, limit):
610 _Verbose.__init__(self)
611 self.mon = RLock()
612 self.rc = Condition(self.mon)
613 self.wc = Condition(self.mon)
614 self.limit = limit
615 self.queue = []
616
617 def put(self, item):
618 self.mon.acquire()
619 while len(self.queue) >= self.limit:
620 self._note("put(%s): queue full", item)
621 self.wc.wait()
622 self.queue.append(item)
623 self._note("put(%s): appended, length now %d",
624 item, len(self.queue))
625 self.rc.notify()
626 self.mon.release()
627
628 def get(self):
629 self.mon.acquire()
630 while not self.queue:
631 self._note("get(): queue empty")
632 self.rc.wait()
633 item = self.queue[0]
634 del self.queue[0]
635 self._note("get(): got %s, %d left", item, len(self.queue))
636 self.wc.notify()
637 self.mon.release()
638 return item
639
640 class ProducerThread(Thread):
641
642 def __init__(self, queue, quota):
643 Thread.__init__(self, name="Producer")
644 self.queue = queue
645 self.quota = quota
646
647 def run(self):
Guido van Rossumb26a1b41998-05-20 17:05:52 +0000648 from random import random
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000649 counter = 0
650 while counter < self.quota:
651 counter = counter + 1
652 self.queue.put("%s.%d" % (self.getName(), counter))
653 _sleep(random() * 0.00001)
654
655
656 class ConsumerThread(Thread):
657
658 def __init__(self, queue, count):
659 Thread.__init__(self, name="Consumer")
660 self.queue = queue
661 self.count = count
662
663 def run(self):
664 while self.count > 0:
665 item = self.queue.get()
666 print item
667 self.count = self.count - 1
668
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000669 NP = 3
670 QL = 4
671 NI = 5
672
673 Q = BoundedQueue(QL)
674 P = []
675 for i in range(NP):
676 t = ProducerThread(Q, NI)
677 t.setName("Producer-%d" % (i+1))
678 P.append(t)
679 C = ConsumerThread(Q, NI*NP)
680 for t in P:
681 t.start()
682 _sleep(0.000001)
683 C.start()
684 for t in P:
685 t.join()
686 C.join()
687
688if __name__ == '__main__':
689 _test()