view MoinMoin/util/ @ 136:13bce99cba0b

use sorted(), use while True
author Thomas Waldmann <tw AT waldmann-edv DOT de>
date Sun, 20 Mar 2011 02:41:47 +0100
parents 87a2f219a310
children 5bf6d7a2ffcf
line wrap: on
line source
# Copyright: 2006 Alexander Schremmer <alex AT alexanderweb DOT de>
# License: GNU GPL v2 (or any later version), see LICENSE.txt for details.

    Thread monitor - Check the state of all threads.

    Just call activate_hook() as early as possible in program execution.
    Then you can trigger the output of tracebacks of all threads
    by calling trigger_dump().

__all__ = "activate_hook trigger_dump dump_regularly".split()

import sys
import threading
import traceback
from time import sleep
from StringIO import StringIO

class Monitor(object):
    def __init__(self):
        self.enabled = False
        assert hasattr(sys, "_current_frames") # make sure we have py >= 2.5

    def activate_hook(self):
        """ Activates the thread monitor hook. Note that this might interfere
        with any kind of profiler and some debugging extensions. """
        self.enabled = True

    def trigger_dump(self, dumpfile=None):
        """ Triggers the dump of the tracebacks of all threads.
            If dumpfile is specified, it is used as the output file. """
        if not self.enabled:
        dumpfile = dumpfile or sys.stderr
        cur_frames = sys._current_frames()
        for i in cur_frames:
            s = StringIO()
            print >>s, "\nDumping thread (id %s):" % (i, )
            traceback.print_stack(cur_frames[i], file=s)

    def hook_enabled(self):
        """ Returns true if the thread_monitor hook is enabled. """
        return self.enabled

def dump_regularly(seconds):
    """ Dumps the tracebacks every 'seconds' seconds. """

    def background_dumper(seconds):
        while True:

    threading.Thread(target=background_dumper, args=(seconds, )).start()

mon = Monitor()

activate_hook = mon.activate_hook
trigger_dump = mon.trigger_dump
hook_enabled = mon.hook_enabled