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

(yzsuai) #1

I tried, it hung the entire process on my Linux system and killed every thread in the
process on Windows!).


The alternative threading module for threads has no method equivalent to
_thread.exit(), but since all that the latter does is raise a system-exit exception, doing
the same in threading has the same effect—the thread exits immediately and silently,
as in the following sort of code (see testexit-threading.py in the example tree for this
code):


import threading, sys, time

def action():
sys.exit() # or raise SystemExit()
print('not reached')

threading.Thread(target=action).start()
time.sleep(2)
print('Main exit')

On a related note, keep in mind that threads and processes have default lifespan models,
which we explored earlier. By way of review, when child threads are still running, the
two thread modules’ behavior differs—programs on most platforms exit when the pa-
rent thread does under _thread, but not normally under threading unless children are
made daemons. When using processes, children normally outlive their parent. This
different process behavior makes sense if you remember that threads are in-process
function calls, but processes are more independent and autonomous.


When used well, exit status can be used to implement error detection and simple com-
munication protocols in systems composed of command-line scripts. But having said
that, I should underscore that most scripts do simply fall off the end of the source to
exit, and most thread functions simply return; explicit exit calls are generally employed
for exceptional conditions and in limited contexts only. More typically, programs com-
municate with richer tools than integer exit codes; the next section shows how.


Interprocess Communication


As we saw earlier, when scripts spawn threads—tasks that run in parallel within the
program—they can naturally communicate by changing and inspecting names and
objects in shared global memory. This includes both accessible variables and attributes,
as well as referenced mutable objects. As we also saw, some care must be taken to use
locks to synchronize access to shared items that can be updated concurrently. Still,
threads offer a fairly straightforward communication model, and the queue module can
make this nearly automatic for many programs.


Things aren’t quite as simple when scripts start child processes and independent pro-
grams that do not share memory in general. If we limit the kinds of communications
that can happen between programs, many options are available, most of which we’ve


222 | Chapter 5: Parallel System Tools

Free download pdf