Welcome, guest | Sign In | My Account | Store | Cart

The threading module of Python is quite nice to use, but sometimes you'd like to know how long your tasks are already running, so you may react on long running threads. In my example I tried to make creating usual threads more easy also.

Python, 36 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
from threading import *
from mx.DateTime import *

class myThread(Thread):
    def __init__(self, target, args=(), name=None):
        # we need a tuple here
        if type(args)<>type((1,)):
            args = (args,)
        Thread.__init__(self, target=target, name=name, args=args)
        self._uptime = now()
        self.start()

    def getUptime(self):
        return self._uptime

    def __str__(self):
        return self.getName()

def GetThreads():
    " doesn't list mainthread "
    return filter(lambda x: x.getName()<>"MainThread", enumerate())

if __name__=="__main__":
    import time
    def DoSome(s=""):
        print "now it's ", now()
        for i in range(3):
            print s, now()
            time.sleep(1)

    t1 = myThread(DoSome, ("one"))
    t2 = myThread(DoSome, ("two"))

    time.sleep(0.5)
    for t in GetThreads(): 
        print t, t.getUptime()

This solution may be usefull for long running processes like servers where you'd like to use threads but where you aren't sure if all threads are ending. A pending problem in Python is still the fact, that it isn't possible to kill a thread from outside of itself. A receipe to solve this problem would be interesting ;-)

The code uses mx.DateTime, you get it from Marc-Andre Lemburg http://www.lemburg.com/files/python/

2 comments

Leo Pold 19 years, 10 months ago  # | flag

Stopping Threads from outside. This was found at: http://www.opendocspublishing.com/pyqt/index.lxp?lxpwrap=x3738.htm

Killing or stopping threads from outside the threads is not supported in Python, but you can create a global variable, stop, to circumvent this. In the threads themselves, you then check whether stop is true.

Greetings, Leo