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

(yzsuai) #1

uses time.sleep so that the main thread doesn't die too early--
this kills all other threads on some platforms; stdout is shared:
thread outputs may be intermixed in this version arbitrarily.
"""


import _thread as thread, time


def counter(myId, count): # function run in threads
for i in range(count):
time.sleep(1) # simulate real work
print('[%s] => %s' % (myId, i))


for i in range(5): # spawn 5 threads
thread.start_new_thread(counter, (i, 5)) # each thread loops 5 times


time.sleep(6)
print('Main thread exiting.') # don't exit too early


Each parallel copy of the counter function simply counts from zero up to four here and
prints a message to standard output for each count.


Notice how this script sleeps for 6 seconds at the end. On Windows and Linux machines
this has been tested on, the main thread shouldn’t exit while any spawned threads are
running if it cares about their work; if it does exit, all spawned threads are immediately
terminated. This differs from processes, where spawned children live on when parents
exit. Without the sleep here, the spawned threads would die almost immediately after
they are started.


This may seem ad hoc, but it isn’t required on all platforms, and programs are usually
structured such that the main thread naturally lives as long as the threads it starts. For
instance, a user interface may start an FTP download running in a thread, but the
download lives a much shorter life than the user interface itself. Later in this section,
we’ll also see different ways to avoid this sleep using global locks and flags that let
threads signal their completion.


Moreover, we’ll later find that the threading module both provides a join method that
lets us wait for spawned threads to finish explicitly, and refuses to allow a program to
exit at all if any of its normal threads are still running (which may be useful in this case,
but can require extra work to shut down in others). The multiprocessing module we’ll
meet later in this chapter also allows spawned children to outlive their parents, though
this is largely an artifact of its process-based model.


Now, when Example 5-6 is run on Windows 7 under Python 3.1, here is the output I get:


C:\...\PP4E\System\Threads> python thread-count.py
[1] => 0
[1] => 0
[0] => 0
[1] => 0
[0] => 0
[2] => 0
[3] => 0

192 | Chapter 5: Parallel System Tools

Free download pdf