O'Reilly logo

Python Programming On Win32 by Mark Hammond, Andy Robinson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Python Thread Support

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 threading application.

Here’s a trivial example using the threading 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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required