57  Creating threads

The other feature of the threading module that annoys me is the interface for creating and starting threads. The usual way requires keyword arguments and two steps:

import threading

def function(x, y, z):
    print x, y, z

thread = threading.Thread(target=function, args=[1, 2, 3])
thread.start()

In this example, creating the thread has no immediate effect. But when you invoke start, the new thread executes the target function with the given arguments. This is great if you need to do something with the thread before it starts, but I almost never do. Also, I think the keyword arguments target and args are awkward.

Fortunately, we can solve both of these problems with four lines of code.

class Thread(threading.Thread):
    def __init__(self, t, *args):
        threading.Thread.__init__(self, target=t, args=args)
        self.start()

Now we can create threads with a nicer interface, and they start automatically:

thread = Thread(function, 1, 2, 3)

This also lends itself to an idiom I like, which is to create multiple Threads with a list comprehension:

threads = [Thread(function, i, i, i) for i in range(10)]