Python supports threads through a number of built-in modules. For many threading-related tasks, you are likely to find these modules more than adequate, your code is portable across all platforms that support threading, and you have access to the copious documentation and examples available.
The most general-purpose of these modules is the
threading module, which provides an interface
modeled after Java’s threading support. This module provides a
Thread class to manage your threads and also a
number of synchronization objects necessary in any nontrivial
Here’s a trivial example using the
module. Let’s create a new thread as a subclass of the
threading.Thread class and override the
run() method that implements the thread. Each
thread loops five times, printing a message each time. It should be
noted that subclassing the
Thread class is just
one way to implement this thread; it’s also possible to
implement the new thread in a normal function.
The main thread creates three worker threads, then waits for them all
to complete, using the
join() method provided by
the base class:
# SimpleThreads.py # # Trivial example of using the Python threading module. import Threading import time import random class SimpleThread(Threading.Thread): def run(self): for i in range(5): print self, i time.sleep(random.random()) if __name__=='__main__': threads =  for i in range(3): thread = SimpleThread() thread.start() threads.append(thread) # Now we ...