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

(yzsuai) #1

  • The exit status of child process is available after they finish in their exitcode
    attribute.


When run, the output of the main consumer process traces its queue fetches, and the
(indented) output of spawned child producer processes gives process IDs and state.


C:\...\PP4E\System\Processes> multi4.py
start 6296
no data...
no data...
@ 8008 101
posted: [8008, 101]
@ 6068 1
@ 3760 1001
posted: [6068, 1]
@ 8008 102
posted: [3760, 1001]
@ 6068 2
@ 3760 1002
posted: [8008, 102]
@ 8008 103
@ 8008 -
posted: [6068, 2]
@ 6068 3
@ 6068 -
@ 3760 1003
@ 3760 -
posted: [3760, 1002]
posted: [8008, 103]
posted: [6068, 3]
posted: [3760, 1003]
finish 6296 0

If you imagine the “@” lines here as results of long-running operations and the others
as a main GUI thread, the wide relevance of this package may become more apparent.


Starting Independent Programs


As we learned earlier, independent programs generally communicate with system-
global tools such as sockets and the fifo files we studied earlier. Although processes
spawned by multiprocessing can leverage these tools, too, their closer relationship
affords them the host of additional IPC communication devices provided by this
module.


Like threads, multiprocessing is designed to run function calls in parallel, not to start
entirely separate programs directly. Spawned functions might use tools like os.system,
os.popen, and subprocess to start a program if such an operation might block the caller,
but there’s otherwise often no point in starting a process that just starts a program
(you might as well start the program and skip a step). In fact, on Windows,
multiprocessing today uses the same process creation call as subprocess, so there’s little
point in starting two processes to run one.


254 | Chapter 5: Parallel System Tools

Free download pdf