1 """Proposed new threading module, emulating a subset of Java's threading model."""
9 # Rename some stuff so "from threading import *" is safe
18 _start_new_thread
= thread
.start_new_thread
19 _allocate_lock
= thread
.allocate_lock
20 _get_ident
= thread
.get_ident
21 ThreadError
= thread
.error
24 _print_exc
= traceback
.print_exc
27 _StringIO
= StringIO
.StringIO
31 # Debug support (adapted from ihooks.py)
39 def __init__(self
, verbose
=None):
42 self
.__verbose
= verbose
44 def _note(self
, format
, *args
):
46 format
= format
% args
47 format
= "%s: %s\n" % (
48 currentThread().getName(), format
)
49 _sys
.stderr
.write(format
)
52 # Disable this when using "python -O"
54 def __init__(self
, verbose
=None):
56 def _note(self
, *args
):
60 # Synchronization classes
64 def RLock(*args
, **kwargs
):
65 return apply(_RLock
, args
, kwargs
)
67 class _RLock(_Verbose
):
69 def __init__(self
, verbose
=None):
70 _Verbose
.__init
__(self
, verbose
)
71 self
.__block
= _allocate_lock()
76 return "<%s(%s, %d)>" % (
77 self
.__class
__.__name
__,
78 self
.__owner
and self
.__owner
.getName(),
81 def acquire(self
, blocking
=1):
83 if self
.__owner
is me
:
84 self
.__count
= self
.__count
+ 1
86 self
._note
("%s.acquire(%s): recursive success", self
, blocking
)
88 rc
= self
.__block
.acquire(blocking
)
93 self
._note
("%s.acquire(%s): initial succes", self
, blocking
)
96 self
._note
("%s.acquire(%s): failure", self
, blocking
)
101 assert self
.__owner
is me
, "release() of un-acquire()d lock"
102 self
.__count
= count
= self
.__count
- 1
105 self
.__block
.release()
107 self
._note
("%s.release(): final release", self
)
110 self
._note
("%s.release(): non-final release", self
)
112 # Internal methods used by condition variables
114 def _acquire_restore(self
, (count
, owner
)):
115 self
.__block
.acquire()
119 self
._note
("%s._acquire_restore()", self
)
121 def _release_save(self
):
123 self
._note
("%s._release_save()", self
)
128 self
.__block
.release()
129 return (count
, owner
)
132 return self
.__owner
is currentThread()
135 def Condition(*args
, **kwargs
):
136 return apply(_Condition
, args
, kwargs
)
138 class _Condition(_Verbose
):
140 def __init__(self
, lock
=None, verbose
=None):
141 _Verbose
.__init
__(self
, verbose
)
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().
152 self
._release
_save
= lock
._release
_save
153 except AttributeError:
156 self
._acquire
_restore
= lock
._acquire
_restore
157 except AttributeError:
160 self
._is
_owned
= lock
._is
_owned
161 except AttributeError:
166 return "<Condition(%s, %d)>" % (self
.__lock
, len(self
.__waiters
))
168 def _release_save(self
):
169 self
.__lock
.release() # No state to save
171 def _acquire_restore(self
, x
):
172 self
.__lock
.acquire() # Ignore saved state
175 if self
.__lock
.acquire(0):
176 self
.__lock
.release()
181 def wait(self
, timeout
=None):
183 assert self
._is
_owned
(), "wait() of un-acquire()d lock"
184 waiter
= _allocate_lock()
186 self
.__waiters
.append(waiter
)
187 saved_state
= self
._release
_save
()
188 try: # restore state no matter what (e.g., KeyboardInterrupt)
192 self
._note
("%s.wait(): got it", self
)
194 endtime
= _time() + timeout
195 delay
= 0.000001 # 1 usec
197 gotit
= waiter
.acquire(0)
198 if gotit
or _time() >= endtime
:
205 self
._note
("%s.wait(%s): timed out", self
, timeout
)
207 self
.__waiters
.remove(waiter
)
212 self
._note
("%s.wait(%s): got it", self
, timeout
)
214 self
._acquire
_restore
(saved_state
)
216 def notify(self
, n
=1):
218 assert self
._is
_owned
(), "notify() of un-acquire()d lock"
219 __waiters
= self
.__waiters
220 waiters
= __waiters
[:n
]
223 self
._note
("%s.notify(): no waiters", self
)
225 self
._note
("%s.notify(): notifying %d waiter%s", self
, n
,
227 for waiter
in waiters
:
230 __waiters
.remove(waiter
)
235 self
.notify(len(self
.__waiters
))
238 def Semaphore(*args
, **kwargs
):
239 return apply(_Semaphore
, args
, kwargs
)
241 class _Semaphore(_Verbose
):
243 # After Tim Peters' semaphore class, but not quite the same (no maximum)
245 def __init__(self
, value
=1, verbose
=None):
246 assert value
>= 0, "Semaphore initial value must be >= 0"
247 _Verbose
.__init
__(self
, verbose
)
248 self
.__cond
= Condition(Lock())
251 def acquire(self
, blocking
=1):
253 self
.__cond
.acquire()
254 while self
.__value
== 0:
259 self
.__value
= self
.__value
- 1
261 self
.__cond
.release()
265 self
.__cond
.acquire()
266 self
.__value
= self
.__value
+ 1
268 self
.__cond
.release()
271 def Event(*args
, **kwargs
):
272 return apply(_Event
, args
, kwargs
)
274 class _Event(_Verbose
):
276 # After Tim Peters' event class (without is_posted())
278 def __init__(self
, verbose
=None):
279 _Verbose
.__init
__(self
, verbose
)
280 self
.__cond
= Condition(Lock())
287 self
.__cond
.acquire()
289 self
.__cond
.notifyAll()
290 self
.__cond
.release()
293 self
.__cond
.acquire()
295 self
.__cond
.release()
297 def wait(self
, timeout
=None):
298 self
.__cond
.acquire()
300 self
.__cond
.wait(timeout
)
301 self
.__cond
.release()
304 # Helper to generate new thread names
306 def _newname(template
="Thread-%d"):
308 _counter
= _counter
+ 1
309 return template
% _counter
311 # Active thread administration
312 _active_limbo_lock
= _allocate_lock()
317 # Main class for threads
319 class Thread(_Verbose
):
323 def __init__(self
, group
=None, target
=None, name
=None,
324 args
=(), kwargs
={}, verbose
=None):
325 assert group
is None, "group argument must be None for now"
326 _Verbose
.__init
__(self
, verbose
)
327 self
.__target
= target
328 self
.__name
= str(name
or _newname())
330 self
.__kwargs
= kwargs
331 self
.__daemonic
= self
._set
_daemon
()
334 self
.__block
= Condition(Lock())
335 self
.__initialized
= 1
337 def _set_daemon(self
):
338 # Overridden in _MainThread and _DummyThread
339 return currentThread().isDaemon()
342 assert self
.__initialized
, "Thread.__init__() was not called"
349 status
= status
+ " daemon"
350 return "<%s(%s, %s)>" % (self
.__class
__.__name
__, self
.__name
, status
)
353 assert self
.__initialized
, "Thread.__init__() not called"
354 assert not self
.__started
, "thread already started"
356 self
._note
("%s.start(): starting thread", self
)
357 _active_limbo_lock
.acquire()
359 _active_limbo_lock
.release()
360 _start_new_thread(self
.__bootstrap
, ())
362 _sleep(0.000001) # 1 usec, to let the thread run (Solaris hack)
366 apply(self
.__target
, self
.__args
, self
.__kwargs
)
368 def __bootstrap(self
):
371 _active_limbo_lock
.acquire()
372 _active
[_get_ident()] = self
374 _active_limbo_lock
.release()
376 self
._note
("%s.__bootstrap(): thread started", self
)
381 self
._note
("%s.__bootstrap(): raised SystemExit", self
)
384 self
._note
("%s.__bootstrap(): unhandled exception", self
)
387 _sys
.stderr
.write("Exception in thread %s:\n%s\n" %
388 (self
.getName(), s
.getvalue()))
391 self
._note
("%s.__bootstrap(): normal return", self
)
400 self
.__block
.acquire()
402 self
.__block
.notifyAll()
403 self
.__block
.release()
406 _active_limbo_lock
.acquire()
407 del _active
[_get_ident()]
408 _active_limbo_lock
.release()
410 def join(self
, timeout
=None):
411 assert self
.__initialized
, "Thread.__init__() not called"
412 assert self
.__started
, "cannot join thread before it is started"
413 assert self
is not currentThread(), "cannot join current thread"
415 if not self
.__stopped
:
416 self
._note
("%s.join(): waiting until thread stops", self
)
417 self
.__block
.acquire()
419 while not self
.__stopped
:
422 self
._note
("%s.join(): thread stopped", self
)
424 deadline
= _time() + timeout
425 while not self
.__stopped
:
426 delay
= deadline
- _time()
429 self
._note
("%s.join(): timed out", self
)
431 self
.__block
.wait(delay
)
434 self
._note
("%s.join(): thread stopped", self
)
435 self
.__block
.release()
438 assert self
.__initialized
, "Thread.__init__() not called"
441 def setName(self
, name
):
442 assert self
.__initialized
, "Thread.__init__() not called"
443 self
.__name
= str(name
)
446 assert self
.__initialized
, "Thread.__init__() not called"
447 return self
.__started
and not self
.__stopped
450 assert self
.__initialized
, "Thread.__init__() not called"
451 return self
.__daemonic
453 def setDaemon(self
, daemonic
):
454 assert self
.__initialized
, "Thread.__init__() not called"
455 assert not self
.__started
, "cannot set daemon status of active thread"
456 self
.__daemonic
= daemonic
459 # Special thread class to represent the main thread
460 # This is garbage collected through an exit handler
462 class _MainThread(Thread
):
465 Thread
.__init
__(self
, name
="MainThread")
466 self
._Thread
__started
= 1
467 _active_limbo_lock
.acquire()
468 _active
[_get_ident()] = self
469 _active_limbo_lock
.release()
471 atexit
.register(self
.__exitfunc
)
473 def _set_daemon(self
):
476 def __exitfunc(self
):
478 t
= _pickSomeNonDaemonThread()
481 self
._note
("%s: waiting for other threads", self
)
484 t
= _pickSomeNonDaemonThread()
486 self
._note
("%s: exiting", self
)
487 self
._Thread
__delete
()
489 def _pickSomeNonDaemonThread():
490 for t
in enumerate():
491 if not t
.isDaemon() and t
.isAlive():
496 # Dummy thread class to represent threads not started here.
497 # These aren't garbage collected when they die,
498 # nor can they be waited for.
499 # Their purpose is to return *something* from currentThread().
500 # They are marked as daemon threads so we won't wait for them
501 # when we exit (conform previous semantics).
503 class _DummyThread(Thread
):
506 Thread
.__init
__(self
, name
=_newname("Dummy-%d"))
507 self
._Thread
__started
= 1
508 _active_limbo_lock
.acquire()
509 _active
[_get_ident()] = self
510 _active_limbo_lock
.release()
512 def _set_daemon(self
):
516 assert 0, "cannot join a dummy thread"
519 # Global API functions
523 return _active
[_get_ident()]
525 ##print "currentThread(): no current thread for", _get_ident()
526 return _DummyThread()
529 _active_limbo_lock
.acquire()
530 count
= len(_active
) + len(_limbo
)
531 _active_limbo_lock
.release()
535 _active_limbo_lock
.acquire()
536 active
= _active
.values() + _limbo
.values()
537 _active_limbo_lock
.release()
541 # Create the main thread object
552 class BoundedQueue(_Verbose
):
554 def __init__(self
, limit
):
555 _Verbose
.__init
__(self
)
557 self
.rc
= Condition(self
.mon
)
558 self
.wc
= Condition(self
.mon
)
564 while len(self
.queue
) >= self
.limit
:
565 self
._note
("put(%s): queue full", item
)
567 self
.queue
.append(item
)
568 self
._note
("put(%s): appended, length now %d",
569 item
, len(self
.queue
))
575 while not self
.queue
:
576 self
._note
("get(): queue empty")
580 self
._note
("get(): got %s, %d left", item
, len(self
.queue
))
585 class ProducerThread(Thread
):
587 def __init__(self
, queue
, quota
):
588 Thread
.__init
__(self
, name
="Producer")
593 from random
import random
595 while counter
< self
.quota
:
596 counter
= counter
+ 1
597 self
.queue
.put("%s.%d" % (self
.getName(), counter
))
598 _sleep(random() * 0.00001)
601 class ConsumerThread(Thread
):
603 def __init__(self
, queue
, count
):
604 Thread
.__init
__(self
, name
="Consumer")
609 while self
.count
> 0:
610 item
= self
.queue
.get()
612 self
.count
= self
.count
- 1
623 t
= ProducerThread(Q
, NI
)
624 t
.setName("Producer-%d" % (i
+1))
626 C
= ConsumerThread(Q
, NI
*NP
)
635 if __name__
== '__main__':