No threading.start_new_thread(), useful addition?

Laszlo Nagy gandalf at shopzeus.com
Fri Oct 9 12:06:03 EDT 2009


> I personally find it much cleaner this way. Also, why should any code care
> in which thread it is executed? Why should I have to derive a class from
> some other only because I want to run one of its functions in a separate
> thread?
>
>   
I think you are right! Especially that you can (and probably will) call 
other methods from your thread. For example, functions from the standard 
library. Or use methods of objects that where created in a different 
thread. I think we can say, you must call methods of other (not Thread) 
objects if you ever want to do something useful in your thread.

Now I'm beginnig to agree with you, Ulrich. We have 
threading.enumerate() - it can be used to list active threads. So if you 
only want to start a function in a separate thread, then you do not 
really need the Thread object. Then we do you HAVE TO create a Thread 
object explicitely?

Of course you can easily create a nice decorator like this:

import threading
def threadlaunch(func):
    def launcher(*args,**kwargs):
        thr = threading.Thread(target=func,args=args,kwargs=kwargs)
        thr.start()
        return thr
    return launcher

And then do something like:

import time
@threadlaunch
def print_something(w,s):
    print "please wait..."
    time.sleep(w)
    print s
thr = print_something(3,"Test")
print "started print_something in",thr

How about that? (Or was it your concern that it is not part of the 
standard library?)

Best,

   Laszlo




More information about the Python-list mailing list