child.join() # wait for child exit
print('parent exit')
When run on Windows, here’s this script’s output—one child passes an object to the
parent, and the other both sends and receives on the same pipe:
C:\...\PP4E\System\Processes> multi2.py
parent got: ['spam', 42, 'eggs']
parent got: {'name': 'Bob', 'spam': 42}
talker got: {'ss', 'aa', 'pp', 'mm'}
parent exit
This module’s pipe objects make communication between two processes portable (and
nearly trivial).
Shared memory and globals
Example 5-31 uses shared memory to serve as both inputs and outputs of spawned
processes. To make this work portably, we must create objects defined by the package
and pass them to Process constructors. The last test in this demo (“loop4”) probably
represents the most common use case for shared memory—that of distributing com-
putation work to multiple parallel processes.
Example 5-31. PP4E\System\Processes\multi3.py
"""
Use multiprocess shared memory objects to communicate.
Passed objects are shared, but globals are not on Windows.
Last test here reflects common use case: distributing work.
"""
import os
from multiprocessing import Process, Value, Array
procs = 3
count = 0 # per-process globals, not shared
def showdata(label, val, arr):
"""
print data values in this process
"""
msg = '%-12s: pid:%4s, global:%s, value:%s, array:%s'
print(msg % (label, os.getpid(), count, val.value, list(arr)))
def updater(val, arr):
"""
communicate via shared memory
"""
global count
count += 1 # global count not shared
val.value += 1 # passed in objects are
for i in range(3): arr[i] += 1
if name == 'main':
250 | Chapter 5: Parallel System Tools