to manage threads with high-level class-based objects. Both modules also provide tools
for synchronizing access to shared objects with locks.
This book presents both the _thread and threading modules, and its
examples use both interchangeably. Some Python users would recom-
mend that you always use threading rather than _thread in general. In
fact, the latter was renamed from thread to _thread in 3.X to suggest
such a lesser status for it. Personally, I think that is too extreme (and
this is one reason this book sometimes uses as thread in imports to
retain the original module name). Unless you need the more powerful
tools in threading, the choice is largely arbitrary, and the threading
module’s extra requirements may be unwarranted.
The basic thread module does not impose OOP, and as you’ll see in the
examples of this section, is very straightforward to use. The threading
module may be better for more complex tasks which require per-thread
state retention or joins, but not all threaded programs require its extra
tools, and many use threads in more limited scopes. In fact, this is
roughly the same as comparing the os.walk call and visitor classes we’ll
meet in Chapter 6—both have valid audiences and use cases. The most
general Python rule of thumb applies here as always: keep it simple,
unless it has to be complex.
The _thread Module
Since the basic _thread module is a bit simpler than the more advanced threading
module covered later in this section, let’s look at some of its interfaces first. This module
provides a portable interface to whatever threading system is available in your platform:
its interfaces work the same on Windows, Solaris, SGI, and any system with an installed
pthreads POSIX threads implementation (including Linux and others). Python scripts
that use the Python _thread module work on all of these platforms without changing
their source code.
Basic usage
Let’s start off by experimenting with a script that demonstrates the main thread inter-
faces. The script in Example 5-5 spawns threads until you reply with a q at the console;
it’s similar in spirit to (and a bit simpler than) the script in Example 5-1, but it goes
parallel with threads instead of process forks.
Example 5-5. PP4E\System\Threads\thread1.py
"spawn threads until you type 'q'"
import _thread
def child(tid):
Threads | 189