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

(yzsuai) #1

Each message here is printed from a new thread, which exits almost as soon as it is
started.


Other ways to code threads with _thread


Although the preceding script runs a simple function, any callable object may be run in
the thread, because all threads live in the same process. For instance, a thread can also
run a lambda function or bound method of an object (the following code is part of file
thread-alts.py in the book examples package):


import _thread # all 3 print 4294967296

def action(i): # function run in threads
print(i ** 32)

class Power:
def __init__(self, i):
self.i = i
def action(self): # bound method run in threads
print(self.i ** 32)

_thread.start_new_thread(action, (2,)) # simple function

_thread.start_new_thread((lambda: action(2)), ()) # lambda function to defer

obj = Power(2)
_thread.start_new_thread(obj.action, ()) # bound method object

As we’ll see in larger examples later in this book, bound methods are especially useful
in this role—because they remember both the method function and instance object,
they also give access to state information and class methods for use within and during
the thread.


More fundamentally, because threads all run in the same process, bound methods run
by threads reference the original in-process instance object, not a copy of it. Hence, any
changes to its state made in a thread will be visible to all threads automatically. More-
over, since bound methods of a class instance pass for callables interchangeably with
simple functions, using them in threads this way just works. And as we’ll see later, the
fact that they are normal objects also allows them to be stored freely on shared queues.


Running multiple threads


To really understand the power of threads running in parallel, though, we have to do
something more long-lived in our threads, just as we did earlier for processes. Let’s
mutate the fork-count program of the prior section to use threads. The script in Ex-
ample 5-6 starts 5 copies of its counter function running in parallel threads.


Example 5-6. PP4E\System\Threads\thread-count.py


"""
thread basics: start 5 copies of a function running in parallel;


Threads | 191
Free download pdf