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

(yzsuai) #1

print('Hello from child', os.getpid(), exitstat)
os._exit(exitstat)
print('never reached')


def parent():
while True:
newpid = os.fork() # start a new copy of process
if newpid == 0: # if in copy, run child logic
child() # loop until 'q' console input
else:
pid, status = os.wait()
print('Parent got', pid, status, (status >> 8))
if input() == 'q': break


if name == 'main': parent()


Running this program on Linux, Unix, or Cygwin (remember, fork still doesn’t work
on standard Windows Python as I write the fourth edition of this book) produces the
following sort of results:


[C:\...\PP4E\System\Exits]$ python testexit_fork.py
Hello from child 5828 1
Parent got 5828 256 1

Hello from child 9540 1
Parent got 9540 256 1

Hello from child 3152 1
Parent got 3152 256 1
q

If you study this output closely, you’ll notice that the exit status (the last number prin-
ted) is always the same—the number 1. Because forked processes begin life as copies
of the process that created them, they also have copies of global memory. Because of
that, each forked child gets and changes its own exitstat global variable without
changing any other process’s copy of this variable. At the same time, forked processes
copy and thus share file descriptors, which is why prints go to the same place.


Thread Exits and Shared State


In contrast, threads run in parallel within the same process and share global memory.
Each thread in Example 5-18 changes the single shared global variable, exitstat.


Example 5-18. PP4E\System\Exits\testexit_thread.py


"""
spawn threads to watch shared global memory change; threads normally exit
when the function they run returns, but _thread.exit() can be called to
exit calling thread; _thread.exit is the same as sys.exit and raising
SystemExit; threads communicate with possibly locked global vars; caveat:
may need to make print/input calls atomic on some platforms--shared stdout;
"""


220 | Chapter 5: Parallel System Tools

Free download pdf