threading.py 30.4 KB
Newer Older
1
"""Thread module emulating a subset of Java's threading model."""
2

3
import sys as _sys
4
import _thread
5 6

from time import time as _time, sleep as _sleep
7
from traceback import format_exc as _format_exc
8
from collections import deque
9

10 11 12 13 14 15 16 17 18 19 20
# Note regarding PEP 8 compliant names
#  This threading model was originally inspired by Java, and inherited
# the convention of camelCase function and method names from that
# language. Those originaly names are not in any imminent danger of
# being deprecated (even for Py3k),so this module provides them as an
# alias for the PEP 8 compliant names
# Note that using the new PEP 8 compliant names facilitates substitution
# with the multiprocessing module, which doesn't provide the old
# Java inspired names.


21
# Rename some stuff so "from threading import *" is safe
22
__all__ = ['active_count', 'Condition', 'current_thread', 'enumerate', 'Event',
23
           'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Thread',
24
           'Timer', 'setprofile', 'settrace', 'local', 'stack_size']
25

26 27 28 29
_start_new_thread = _thread.start_new_thread
_allocate_lock = _thread.allocate_lock
_get_ident = _thread.get_ident
ThreadError = _thread.error
30 31 32 33
try:
    _CRLock = _thread.RLock
except AttributeError:
    _CRLock = None
34
TIMEOUT_MAX = _thread.TIMEOUT_MAX
35
del _thread
36 37


38 39 40 41 42
# Debug support (adapted from ihooks.py).
# All the major classes here derive from _Verbose.  We force that to
# be a new-style class so that all the major classes here are new-style.
# This helps debugging (type(instance) is more revealing for instances
# of new-style classes).
43

44
_VERBOSE = False
45 46 47

if __debug__:

48
    class _Verbose(object):
49 50 51 52

        def __init__(self, verbose=None):
            if verbose is None:
                verbose = _VERBOSE
53
            self._verbose = verbose
54 55

        def _note(self, format, *args):
56
            if self._verbose:
57 58
                format = format % args
                format = "%s: %s\n" % (
59
                    current_thread().name, format)
60 61 62 63
                _sys.stderr.write(format)

else:
    # Disable this when using "python -O"
64
    class _Verbose(object):
65 66 67 68 69
        def __init__(self, verbose=None):
            pass
        def _note(self, *args):
            pass

70 71 72 73 74 75 76 77
# Support for profile and trace hooks

_profile_hook = None
_trace_hook = None

def setprofile(func):
    global _profile_hook
    _profile_hook = func
Tim Peters's avatar
Tim Peters committed
78

79 80 81
def settrace(func):
    global _trace_hook
    _trace_hook = func
82 83 84 85 86

# Synchronization classes

Lock = _allocate_lock

87 88 89 90 91 92
def RLock(verbose=None, *args, **kwargs):
    if verbose is None:
        verbose = _VERBOSE
    if (__debug__ and verbose) or _CRLock is None:
        return _PyRLock(verbose, *args, **kwargs)
    return _CRLock(*args, **kwargs)
93 94

class _RLock(_Verbose):
Tim Peters's avatar
Tim Peters committed
95

96 97
    def __init__(self, verbose=None):
        _Verbose.__init__(self, verbose)
98 99 100
        self._block = _allocate_lock()
        self._owner = None
        self._count = 0
101 102

    def __repr__(self):
103
        owner = self._owner
104 105 106 107 108 109
        try:
            owner = _active[owner].name
        except KeyError:
            pass
        return "<%s owner=%r count=%d>" % (
                self.__class__.__name__, owner, self._count)
110

111
    def acquire(self, blocking=True, timeout=-1):
112 113
        me = _get_ident()
        if self._owner == me:
114
            self._count = self._count + 1
115 116 117
            if __debug__:
                self._note("%s.acquire(%s): recursive success", self, blocking)
            return 1
118
        rc = self._block.acquire(blocking, timeout)
119
        if rc:
120 121
            self._owner = me
            self._count = 1
122
            if __debug__:
123
                self._note("%s.acquire(%s): initial success", self, blocking)
124 125 126 127 128
        else:
            if __debug__:
                self._note("%s.acquire(%s): failure", self, blocking)
        return rc

129 130
    __enter__ = acquire

131
    def release(self):
132
        if self._owner != _get_ident():
Georg Brandl's avatar
Georg Brandl committed
133
            raise RuntimeError("cannot release un-acquired lock")
134
        self._count = count = self._count - 1
135
        if not count:
136 137
            self._owner = None
            self._block.release()
138 139 140 141 142 143
            if __debug__:
                self._note("%s.release(): final release", self)
        else:
            if __debug__:
                self._note("%s.release(): non-final release", self)

144 145 146
    def __exit__(self, t, v, tb):
        self.release()

147 148
    # Internal methods used by condition variables

149
    def _acquire_restore(self, state):
150 151
        self._block.acquire()
        self._count, self._owner = state
152 153 154 155 156 157
        if __debug__:
            self._note("%s._acquire_restore()", self)

    def _release_save(self):
        if __debug__:
            self._note("%s._release_save()", self)
158 159 160 161 162
        count = self._count
        self._count = 0
        owner = self._owner
        self._owner = None
        self._block.release()
163 164 165
        return (count, owner)

    def _is_owned(self):
166
        return self._owner == _get_ident()
167

168 169
_PyRLock = _RLock

170 171

def Condition(*args, **kwargs):
172
    return _Condition(*args, **kwargs)
173 174 175 176 177 178 179

class _Condition(_Verbose):

    def __init__(self, lock=None, verbose=None):
        _Verbose.__init__(self, verbose)
        if lock is None:
            lock = RLock()
180
        self._lock = lock
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
        # Export the lock's acquire() and release() methods
        self.acquire = lock.acquire
        self.release = lock.release
        # If the lock defines _release_save() and/or _acquire_restore(),
        # these override the default implementations (which just call
        # release() and acquire() on the lock).  Ditto for _is_owned().
        try:
            self._release_save = lock._release_save
        except AttributeError:
            pass
        try:
            self._acquire_restore = lock._acquire_restore
        except AttributeError:
            pass
        try:
            self._is_owned = lock._is_owned
        except AttributeError:
            pass
199
        self._waiters = []
200

201
    def __enter__(self):
202
        return self._lock.__enter__()
203

204
    def __exit__(self, *args):
205
        return self._lock.__exit__(*args)
206

207
    def __repr__(self):
208
        return "<Condition(%s, %d)>" % (self._lock, len(self._waiters))
209 210

    def _release_save(self):
211
        self._lock.release()           # No state to save
212 213

    def _acquire_restore(self, x):
214
        self._lock.acquire()           # Ignore saved state
215 216

    def _is_owned(self):
217
        # Return True if lock is owned by current_thread.
Jeremy Hylton's avatar
Jeremy Hylton committed
218
        # This method is called only if __lock doesn't have _is_owned().
219 220
        if self._lock.acquire(0):
            self._lock.release()
221
            return False
222
        else:
223
            return True
224 225

    def wait(self, timeout=None):
226
        if not self._is_owned():
Georg Brandl's avatar
Georg Brandl committed
227
            raise RuntimeError("cannot wait on un-acquired lock")
228 229
        waiter = _allocate_lock()
        waiter.acquire()
230
        self._waiters.append(waiter)
231
        saved_state = self._release_save()
232 233 234
        try:    # restore state no matter what (e.g., KeyboardInterrupt)
            if timeout is None:
                waiter.acquire()
235
                if __debug__:
236
                    self._note("%s.wait(): got it", self)
237
            else:
238 239 240 241
                if timeout > 0:
                    gotit = waiter.acquire(True, timeout)
                else:
                    gotit = waiter.acquire(False)
242 243 244 245
                if not gotit:
                    if __debug__:
                        self._note("%s.wait(%s): timed out", self, timeout)
                    try:
246
                        self._waiters.remove(waiter)
247 248 249 250 251 252 253
                    except ValueError:
                        pass
                else:
                    if __debug__:
                        self._note("%s.wait(%s): got it", self, timeout)
        finally:
            self._acquire_restore(saved_state)
254 255

    def notify(self, n=1):
256
        if not self._is_owned():
Georg Brandl's avatar
Georg Brandl committed
257
            raise RuntimeError("cannot notify on un-acquired lock")
258
        __waiters = self._waiters
259 260 261 262 263 264 265 266 267 268 269 270 271 272
        waiters = __waiters[:n]
        if not waiters:
            if __debug__:
                self._note("%s.notify(): no waiters", self)
            return
        self._note("%s.notify(): notifying %d waiter%s", self, n,
                   n!=1 and "s" or "")
        for waiter in waiters:
            waiter.release()
            try:
                __waiters.remove(waiter)
            except ValueError:
                pass

273
    def notify_all(self):
274
        self.notify(len(self._waiters))
275

276 277
    notifyAll = notify_all

278 279

def Semaphore(*args, **kwargs):
280
    return _Semaphore(*args, **kwargs)
281 282 283

class _Semaphore(_Verbose):

284
    # After Tim Peters' semaphore class, but not quite the same (no maximum)
285 286

    def __init__(self, value=1, verbose=None):
287 288
        if value < 0:
            raise ValueError("semaphore initial value must be >= 0")
289
        _Verbose.__init__(self, verbose)
290 291
        self._cond = Condition(Lock())
        self._value = value
292

293 294 295
    def acquire(self, blocking=True, timeout=None):
        if not blocking and timeout is not None:
            raise ValueError("can't specify timeout for non-blocking acquire")
296
        rc = False
297
        endtime = None
298 299
        self._cond.acquire()
        while self._value == 0:
300 301
            if not blocking:
                break
302 303
            if __debug__:
                self._note("%s.acquire(%s): blocked waiting, value=%s",
304
                           self, blocking, self._value)
305 306 307 308 309 310 311 312
            if timeout is not None:
                if endtime is None:
                    endtime = _time() + timeout
                else:
                    timeout = endtime - _time()
                    if timeout <= 0:
                        break
            self._cond.wait(timeout)
313
        else:
314
            self._value = self._value - 1
315
            if __debug__:
316
                self._note("%s.acquire: success, value=%s",
317
                           self, self._value)
318
            rc = True
319
        self._cond.release()
320 321
        return rc

322 323
    __enter__ = acquire

324
    def release(self):
325 326
        self._cond.acquire()
        self._value = self._value + 1
327
        if __debug__:
328
            self._note("%s.release: success, value=%s",
329 330 331
                       self, self._value)
        self._cond.notify()
        self._cond.release()
332

333 334 335
    def __exit__(self, t, v, tb):
        self.release()

336

337
def BoundedSemaphore(*args, **kwargs):
338
    return _BoundedSemaphore(*args, **kwargs)
339 340 341 342 343 344 345 346

class _BoundedSemaphore(_Semaphore):
    """Semaphore that checks that # releases is <= # acquires"""
    def __init__(self, value=1, verbose=None):
        _Semaphore.__init__(self, value, verbose)
        self._initial_value = value

    def release(self):
347
        if self._value >= self._initial_value:
348
            raise ValueError("Semaphore released too many times")
349 350 351
        return _Semaphore.release(self)


352
def Event(*args, **kwargs):
353
    return _Event(*args, **kwargs)
354 355 356 357 358 359 360

class _Event(_Verbose):

    # After Tim Peters' event class (without is_posted())

    def __init__(self, verbose=None):
        _Verbose.__init__(self, verbose)
361 362
        self._cond = Condition(Lock())
        self._flag = False
363

364
    def is_set(self):
365
        return self._flag
366

367
    isSet = is_set
368

369
    def set(self):
370 371
        self._cond.acquire()
        try:
372
            self._flag = True
373
            self._cond.notify_all()
374 375
        finally:
            self._cond.release()
376 377

    def clear(self):
378 379
        self._cond.acquire()
        try:
380
            self._flag = False
381 382
        finally:
            self._cond.release()
383 384

    def wait(self, timeout=None):
385 386
        self._cond.acquire()
        try:
387 388
            if not self._flag:
                self._cond.wait(timeout)
Benjamin Peterson's avatar
Benjamin Peterson committed
389
            return self._flag
390 391
        finally:
            self._cond.release()
392 393 394 395 396 397 398 399 400 401

# Helper to generate new thread names
_counter = 0
def _newname(template="Thread-%d"):
    global _counter
    _counter = _counter + 1
    return template % _counter

# Active thread administration
_active_limbo_lock = _allocate_lock()
402
_active = {}    # maps thread id to Thread object
403 404 405 406 407 408 409
_limbo = {}


# Main class for threads

class Thread(_Verbose):

410
    __initialized = False
411 412 413 414 415
    # Need to store a reference to sys.exc_info for printing
    # out exceptions when a thread tries to use a global var. during interp.
    # shutdown and thus raises an exception about trying to perform some
    # operation on/with a NoneType
    __exc_info = _sys.exc_info
416 417 418
    # Keep sys.exc_clear too to clear the exception just before
    # allowing .join() to return.
    #XXX __exc_clear = _sys.exc_clear
419 420

    def __init__(self, group=None, target=None, name=None,
421
                 args=(), kwargs=None, verbose=None):
422
        assert group is None, "group argument must be None for now"
423
        _Verbose.__init__(self, verbose)
424 425
        if kwargs is None:
            kwargs = {}
426 427 428 429 430
        self._target = target
        self._name = str(name or _newname())
        self._args = args
        self._kwargs = kwargs
        self._daemonic = self._set_daemon()
Georg Brandl's avatar
Georg Brandl committed
431
        self._ident = None
Christian Heimes's avatar
Christian Heimes committed
432
        self._started = Event()
433 434 435
        self._stopped = False
        self._block = Condition(Lock())
        self._initialized = True
436 437
        # sys.stderr is not stored in the class like
        # sys.exc_info since it can be changed between instances
438
        self._stderr = _sys.stderr
439 440 441

    def _set_daemon(self):
        # Overridden in _MainThread and _DummyThread
442
        return current_thread().daemon
443 444

    def __repr__(self):
445
        assert self._initialized, "Thread.__init__() was not called"
446
        status = "initial"
447
        if self._started.is_set():
448
            status = "started"
449
        if self._stopped:
450
            status = "stopped"
451
        if self._daemonic:
Georg Brandl's avatar
Georg Brandl committed
452 453 454
            status += " daemon"
        if self._ident is not None:
            status += " %s" % self._ident
455
        return "<%s(%s, %s)>" % (self.__class__.__name__, self._name, status)
456 457

    def start(self):
458
        if not self._initialized:
459
            raise RuntimeError("thread.__init__() not called")
Christian Heimes's avatar
Christian Heimes committed
460

461
        if self._started.is_set():
462
            raise RuntimeError("threads can only be started once")
463 464
        if __debug__:
            self._note("%s.start(): starting thread", self)
Benjamin Peterson's avatar
Benjamin Peterson committed
465 466
        with _active_limbo_lock:
            _limbo[self] = self
467 468 469 470 471 472
        try:
            _start_new_thread(self._bootstrap, ())
        except Exception:
            with _active_limbo_lock:
                del _limbo[self]
            raise
Christian Heimes's avatar
Christian Heimes committed
473
        self._started.wait()
474 475

    def run(self):
476 477 478 479 480 481 482
        try:
            if self._target:
                self._target(*self._args, **self._kwargs)
        finally:
            # Avoid a refcycle if the thread is running a function with
            # an argument that has a member that points to the thread.
            del self._target, self._args, self._kwargs
483

484
    def _bootstrap(self):
485 486 487 488 489
        # Wrapper around the real bootstrap code that ignores
        # exceptions during interpreter cleanup.  Those typically
        # happen when a daemon thread wakes up at an unfortunate
        # moment, finds the world around it destroyed, and raises some
        # random exception *** while trying to report the exception in
Christian Heimes's avatar
Christian Heimes committed
490
        # _bootstrap_inner() below ***.  Those random exceptions
491 492 493
        # don't help anybody, and they confuse users, so we suppress
        # them.  We suppress them only when it appears that the world
        # indeed has already been destroyed, so that exceptions in
Christian Heimes's avatar
Christian Heimes committed
494
        # _bootstrap_inner() during normal business hours are properly
495 496 497
        # reported.  Also, we only suppress them for daemonic threads;
        # if a non-daemonic encounters this, something else is wrong.
        try:
498
            self._bootstrap_inner()
499
        except:
500
            if self._daemonic and _sys is None:
501 502 503
                return
            raise

Benjamin Peterson's avatar
Benjamin Peterson committed
504 505 506
    def _set_ident(self):
        self._ident = _get_ident()

507
    def _bootstrap_inner(self):
508
        try:
Benjamin Peterson's avatar
Benjamin Peterson committed
509
            self._set_ident()
Christian Heimes's avatar
Christian Heimes committed
510
            self._started.set()
Benjamin Peterson's avatar
Benjamin Peterson committed
511 512 513
            with _active_limbo_lock:
                _active[self._ident] = self
                del _limbo[self]
514
            if __debug__:
Christian Heimes's avatar
Christian Heimes committed
515
                self._note("%s._bootstrap(): thread started", self)
516 517

            if _trace_hook:
Christian Heimes's avatar
Christian Heimes committed
518
                self._note("%s._bootstrap(): registering trace hook", self)
519 520
                _sys.settrace(_trace_hook)
            if _profile_hook:
Christian Heimes's avatar
Christian Heimes committed
521
                self._note("%s._bootstrap(): registering profile hook", self)
522
                _sys.setprofile(_profile_hook)
Tim Peters's avatar
Tim Peters committed
523

524 525 526 527
            try:
                self.run()
            except SystemExit:
                if __debug__:
Christian Heimes's avatar
Christian Heimes committed
528
                    self._note("%s._bootstrap(): raised SystemExit", self)
529 530
            except:
                if __debug__:
Christian Heimes's avatar
Christian Heimes committed
531
                    self._note("%s._bootstrap(): unhandled exception", self)
532
                # If sys.stderr is no more (most likely from interpreter
533
                # shutdown) use self._stderr.  Otherwise still use sys (as in
534 535 536 537
                # _sys) in case sys.stderr was redefined since the creation of
                # self.
                if _sys:
                    _sys.stderr.write("Exception in thread %s:\n%s\n" %
538
                                      (self.name, _format_exc()))
539 540 541 542
                else:
                    # Do the best job possible w/o a huge amt. of code to
                    # approximate a traceback (code ideas from
                    # Lib/traceback.py)
543
                    exc_type, exc_value, exc_tb = self._exc_info()
544
                    try:
545
                        print((
546
                            "Exception in thread " + self.name +
547
                            " (most likely raised during interpreter shutdown):"), file=self._stderr)
548
                        print((
549
                            "Traceback (most recent call last):"), file=self._stderr)
550
                        while exc_tb:
551
                            print((
552 553 554
                                '  File "%s", line %s, in %s' %
                                (exc_tb.tb_frame.f_code.co_filename,
                                    exc_tb.tb_lineno,
555
                                    exc_tb.tb_frame.f_code.co_name)), file=self._stderr)
556
                            exc_tb = exc_tb.tb_next
557
                        print(("%s: %s" % (exc_type, exc_value)), file=self._stderr)
558 559 560 561
                    # Make sure that exc_tb gets deleted since it is a memory
                    # hog; deleting everything else is just for thoroughness
                    finally:
                        del exc_type, exc_value, exc_tb
562 563
            else:
                if __debug__:
Christian Heimes's avatar
Christian Heimes committed
564
                    self._note("%s._bootstrap(): normal return", self)
565 566 567 568 569 570 571
            finally:
                # Prevent a race in
                # test_threading.test_no_refcycle_through_target when
                # the exception keeps the target alive past when we
                # assert that it's dead.
                #XXX self.__exc_clear()
                pass
572
        finally:
573 574 575
            with _active_limbo_lock:
                self._stop()
                try:
Georg Brandl's avatar
Georg Brandl committed
576
                    # We don't call self._delete() because it also
577 578 579 580
                    # grabs _active_limbo_lock.
                    del _active[_get_ident()]
                except:
                    pass
581

582
    def _stop(self):
583 584
        self._block.acquire()
        self._stopped = True
585
        self._block.notify_all()
586
        self._block.release()
587

588
    def _delete(self):
589 590
        "Remove current thread from the dict of currently running threads."

591
        # Notes about running with _dummy_thread:
592
        #
593
        # Must take care to not raise an exception if _dummy_thread is being
594
        # used (and thus this module is being used as an instance of
595 596
        # dummy_threading).  _dummy_thread.get_ident() always returns -1 since
        # there is only one thread if _dummy_thread is being used.  Thus
597 598 599 600 601
        # len(_active) is always <= 1 here, and any Thread instance created
        # overwrites the (if any) thread currently registered in _active.
        #
        # An instance of _MainThread is always created by 'threading'.  This
        # gets overwritten the instant an instance of Thread is created; both
602
        # threads return -1 from _dummy_thread.get_ident() and thus have the
603 604 605 606 607 608 609 610 611
        # same key in the dict.  So when the _MainThread instance created by
        # 'threading' tries to clean itself up when atexit calls this method
        # it gets a KeyError if another Thread instance was created.
        #
        # This all means that KeyError from trying to delete something from
        # _active if dummy_threading is being used is a red herring.  But
        # since it isn't if dummy_threading is *not* being used then don't
        # hide the exception.

612
        try:
Neal Norwitz's avatar
Neal Norwitz committed
613
            with _active_limbo_lock:
614
                del _active[_get_ident()]
Neal Norwitz's avatar
Neal Norwitz committed
615 616 617
                # There must not be any python code between the previous line
                # and after the lock is released.  Otherwise a tracing function
                # could try to acquire the lock again in the same thread, (in
618
                # current_thread()), and would block.
Neal Norwitz's avatar
Neal Norwitz committed
619 620 621
        except KeyError:
            if 'dummy_threading' not in _sys.modules:
                raise
622 623

    def join(self, timeout=None):
624
        if not self._initialized:
625
            raise RuntimeError("Thread.__init__() not called")
626
        if not self._started.is_set():
627
            raise RuntimeError("cannot join thread before it is started")
628
        if self is current_thread():
629 630
            raise RuntimeError("cannot join current thread")

631
        if __debug__:
632
            if not self._stopped:
633
                self._note("%s.join(): waiting until thread stops", self)
634 635 636

        self._block.acquire()
        try:
637
            if timeout is None:
638 639
                while not self._stopped:
                    self._block.wait()
640 641
                if __debug__:
                    self._note("%s.join(): thread stopped", self)
642 643
            else:
                deadline = _time() + timeout
644
                while not self._stopped:
645 646 647 648 649
                    delay = deadline - _time()
                    if delay <= 0:
                        if __debug__:
                            self._note("%s.join(): timed out", self)
                        break
650
                    self._block.wait(delay)
651 652 653
                else:
                    if __debug__:
                        self._note("%s.join(): thread stopped", self)
654 655
        finally:
            self._block.release()
656

657 658
    @property
    def name(self):
659 660
        assert self._initialized, "Thread.__init__() not called"
        return self._name
661

662 663
    @name.setter
    def name(self, name):
664 665
        assert self._initialized, "Thread.__init__() not called"
        self._name = str(name)
666

667 668
    @property
    def ident(self):
Georg Brandl's avatar
Georg Brandl committed
669 670 671
        assert self._initialized, "Thread.__init__() not called"
        return self._ident

672
    def is_alive(self):
673
        assert self._initialized, "Thread.__init__() not called"
674
        return self._started.is_set() and not self._stopped
Tim Peters's avatar
Tim Peters committed
675

676
    isAlive = is_alive
677

678 679
    @property
    def daemon(self):
680 681
        assert self._initialized, "Thread.__init__() not called"
        return self._daemonic
682

683 684
    @daemon.setter
    def daemon(self, daemonic):
685
        if not self._initialized:
686
            raise RuntimeError("Thread.__init__() not called")
687
        if self._started.is_set():
688
            raise RuntimeError("cannot set daemon status of active thread");
689
        self._daemonic = daemonic
690

691 692 693 694 695 696 697 698 699 700 701 702
    def isDaemon(self):
        return self.daemon

    def setDaemon(self, daemonic):
        self.daemon = daemonic

    def getName(self):
        return self.name

    def setName(self, name):
        self.name = name

703 704 705 706 707 708 709
# The timer class was contributed by Itamar Shtull-Trauring

def Timer(*args, **kwargs):
    return _Timer(*args, **kwargs)

class _Timer(Thread):
    """Call a function after a specified number of seconds:
Tim Peters's avatar
Tim Peters committed
710

711 712 713 714
    t = Timer(30.0, f, args=[], kwargs={})
    t.start()
    t.cancel() # stop the timer's action if it's still waiting
    """
Tim Peters's avatar
Tim Peters committed
715

716 717 718 719 720 721 722
    def __init__(self, interval, function, args=[], kwargs={}):
        Thread.__init__(self)
        self.interval = interval
        self.function = function
        self.args = args
        self.kwargs = kwargs
        self.finished = Event()
Tim Peters's avatar
Tim Peters committed
723

724 725 726
    def cancel(self):
        """Stop the timer if it hasn't finished yet"""
        self.finished.set()
Tim Peters's avatar
Tim Peters committed
727

728 729
    def run(self):
        self.finished.wait(self.interval)
730
        if not self.finished.is_set():
731 732
            self.function(*self.args, **self.kwargs)
        self.finished.set()
733 734 735 736 737 738 739 740

# Special thread class to represent the main thread
# This is garbage collected through an exit handler

class _MainThread(Thread):

    def __init__(self):
        Thread.__init__(self, name="MainThread")
Christian Heimes's avatar
Christian Heimes committed
741
        self._started.set()
Benjamin Peterson's avatar
Benjamin Peterson committed
742 743 744
        self._set_ident()
        with _active_limbo_lock:
            _active[self._ident] = self
745 746

    def _set_daemon(self):
747
        return False
748

749
    def _exitfunc(self):
750
        self._stop()
751 752 753 754 755 756 757 758 759
        t = _pickSomeNonDaemonThread()
        if t:
            if __debug__:
                self._note("%s: waiting for other threads", self)
        while t:
            t.join()
            t = _pickSomeNonDaemonThread()
        if __debug__:
            self._note("%s: exiting", self)
760
        self._delete()
761 762 763

def _pickSomeNonDaemonThread():
    for t in enumerate():
764
        if not t.daemon and t.is_alive():
765 766 767 768 769
            return t
    return None


# Dummy thread class to represent threads not started here.
770
# These aren't garbage collected when they die, nor can they be waited for.
771
# If they invoke anything in threading.py that calls current_thread(), they
772
# leave an entry in the _active dict forever after.
773
# Their purpose is to return *something* from current_thread().
774 775 776 777
# They are marked as daemon threads so we won't wait for them
# when we exit (conform previous semantics).

class _DummyThread(Thread):
Tim Peters's avatar
Tim Peters committed
778

779 780
    def __init__(self):
        Thread.__init__(self, name=_newname("Dummy-%d"))
781 782 783 784

        # Thread.__block consumes an OS-level locking primitive, which
        # can never be used by a _DummyThread.  Since a _DummyThread
        # instance is immortal, that's bad, so release this resource.
785
        del self._block
786

Christian Heimes's avatar
Christian Heimes committed
787 788

        self._started.set()
Benjamin Peterson's avatar
Benjamin Peterson committed
789 790 791
        self._set_ident()
        with _active_limbo_lock:
            _active[self._ident] = self
792 793

    def _set_daemon(self):
794
        return True
795

796
    def join(self, timeout=None):
797
        assert False, "cannot join a dummy thread"
798 799 800 801


# Global API functions

802
def current_thread():
803 804 805
    try:
        return _active[_get_ident()]
    except KeyError:
806
        ##print "current_thread(): no current thread for", _get_ident()
807 808
        return _DummyThread()

809
currentThread = current_thread
810

811
def active_count():
Benjamin Peterson's avatar
Benjamin Peterson committed
812 813
    with _active_limbo_lock:
        return len(_active) + len(_limbo)
814

815
activeCount = active_count
816

817 818 819 820
def _enumerate():
    # Same as enumerate(), but without the lock. Internal use only.
    return list(_active.values()) + list(_limbo.values())

821
def enumerate():
Benjamin Peterson's avatar
Benjamin Peterson committed
822 823
    with _active_limbo_lock:
        return list(_active.values()) + list(_limbo.values())
824

825
from _thread import stack_size
826

827 828 829
# Create the main thread object,
# and make it available for the interpreter
# (Py_Main) as threading._shutdown.
830

831
_shutdown = _MainThread()._exitfunc
832

833 834 835 836
# get thread-local implementation, either from the thread
# module, or from the python fallback

try:
837
    from _thread import _local as local
838 839 840
except ImportError:
    from _threading_local import local

841

Jesse Noller's avatar
Jesse Noller committed
842 843 844 845 846 847 848 849 850 851 852 853 854 855
def _after_fork():
    # This function is called by Python/ceval.c:PyEval_ReInitThreads which
    # is called from PyOS_AfterFork.  Here we cleanup threading module state
    # that should not exist after a fork.

    # Reset _active_limbo_lock, in case we forked while the lock was held
    # by another (non-forked) thread.  http://bugs.python.org/issue874900
    global _active_limbo_lock
    _active_limbo_lock = _allocate_lock()

    # fork() only copied the current thread; clear references to others.
    new_active = {}
    current = current_thread()
    with _active_limbo_lock:
856
        for thread in _active.values():
Jesse Noller's avatar
Jesse Noller committed
857
            if thread is current:
858 859 860 861
                # There is only one active thread. We reset the ident to
                # its new value since it can have changed.
                ident = _get_ident()
                thread._ident = ident
Jesse Noller's avatar
Jesse Noller committed
862 863 864 865 866 867
                new_active[ident] = thread
            else:
                # All the others are already stopped.
                # We don't call _Thread__stop() because it tries to acquire
                # thread._Thread__block which could also have been held while
                # we forked.
868
                thread._stopped = True
Jesse Noller's avatar
Jesse Noller committed
869 870 871 872 873 874 875

        _limbo.clear()
        _active.clear()
        _active.update(new_active)
        assert len(_active) == 1


876 877 878 879 880 881 882 883 884 885 886 887
# Self-test code

def _test():

    class BoundedQueue(_Verbose):

        def __init__(self, limit):
            _Verbose.__init__(self)
            self.mon = RLock()
            self.rc = Condition(self.mon)
            self.wc = Condition(self.mon)
            self.limit = limit
888
            self.queue = deque()
889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905

        def put(self, item):
            self.mon.acquire()
            while len(self.queue) >= self.limit:
                self._note("put(%s): queue full", item)
                self.wc.wait()
            self.queue.append(item)
            self._note("put(%s): appended, length now %d",
                       item, len(self.queue))
            self.rc.notify()
            self.mon.release()

        def get(self):
            self.mon.acquire()
            while not self.queue:
                self._note("get(): queue empty")
                self.rc.wait()
906
            item = self.queue.popleft()
907 908 909 910 911 912 913 914 915 916 917 918 919
            self._note("get(): got %s, %d left", item, len(self.queue))
            self.wc.notify()
            self.mon.release()
            return item

    class ProducerThread(Thread):

        def __init__(self, queue, quota):
            Thread.__init__(self, name="Producer")
            self.queue = queue
            self.quota = quota

        def run(self):
920
            from random import random
921 922 923
            counter = 0
            while counter < self.quota:
                counter = counter + 1
924
                self.queue.put("%s.%d" % (self.name, counter))
925 926 927 928 929 930 931 932 933 934 935 936 937
                _sleep(random() * 0.00001)


    class ConsumerThread(Thread):

        def __init__(self, queue, count):
            Thread.__init__(self, name="Consumer")
            self.queue = queue
            self.count = count

        def run(self):
            while self.count > 0:
                item = self.queue.get()
938
                print(item)
939 940 941 942 943 944 945 946 947 948
                self.count = self.count - 1

    NP = 3
    QL = 4
    NI = 5

    Q = BoundedQueue(QL)
    P = []
    for i in range(NP):
        t = ProducerThread(Q, NI)
949
        t.name = "Producer-%d" % (i+1)
950 951 952 953 954 955 956 957 958 959 960 961
        P.append(t)
    C = ConsumerThread(Q, NI*NP)
    for t in P:
        t.start()
        _sleep(0.000001)
    C.start()
    for t in P:
        t.join()
    C.join()

if __name__ == '__main__':
    _test()