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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access