[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

print('Hello from thread', tid)


def parent():
i = 0
while True:
i += 1
_thread.start_new_thread(child, (i,))
if input() == 'q': break


parent()


This script really contains only two thread-specific lines: the import of the _thread
module and the thread creation call. To start a thread, we simply call the
_thread.start_new_thread function, no matter what platform we’re programming
on.‡ This call takes a function (or other callable) object and an arguments tuple and
starts a new thread to execute a call to the passed function with the passed arguments.
It’s almost like Python’s function(*args) call syntax, and similarly accepts an optional
keyword arguments dictionary, too, but in this case the function call begins running in
parallel with the rest of the program.


Operationally speaking, the _thread.start_new_thread call itself returns immediately
with no useful value, and the thread it spawns silently exits when the function being
run returns (the return value of the threaded function call is simply ignored). Moreover,
if a function run in a thread raises an uncaught exception, a stack trace is printed and
the thread exits, but the rest of the program continues. With the _thread module, the
entire program exits silently on most platforms when the main thread does (though as
we’ll see later, the threading module may require special handling if child threads are
still running).


In practice, though, it’s almost trivial to use threads in a Python script. Let’s run this
program to launch a few threads; we can run it on both Unix-like platforms and Win-
dows this time, because threads are more portable than process forks—here it is
spawning threads on Windows:


C:\...\PP4E\System\Threads> python thread1.py
Hello from thread 1

Hello from thread 2

Hello from thread 3

Hello from thread 4
q

‡ The _thread examples in this book now all use start_new_thread. This call is also available as
thread.start_new for historical reasons, but this synonym may be removed in a future Python release. As of
Python 3.1, both names are still available, but the help documentation for start_new claims that it is obsolete;
in other words, you should probably prefer the other if you care about the future (and this book must!).


190 | Chapter 5: Parallel System Tools

Free download pdf