Most other Python object types, including classes and simple functions, work fine on
pipes and queues.
Also keep in mind that because they are pickled, objects transferred this way are effec-
tively copied in the receiving process; direct in-place changes to mutable objects’ state
won’t be noticed in the sender. This makes sense if you remember that this package
runs independent processes with their own memory spaces; state cannot be as freely
shared as in threading, regardless of which IPC tools you use.
multiprocessing pipes
To demonstrate the IPC tools listed above, the next three examples implement three
flavors of communication between parent and child processes. Example 5-30 uses a
simple shared pipe object to send and receive data between parent and child processes.
Example 5-30. PP4E\System\Processes\multi2.py
"""
Use multiprocess anonymous pipes to communicate. Returns 2 connection
object representing ends of the pipe: objects are sent on one end and
received on the other, though pipes are bidirectional by default
"""
import os
from multiprocessing import Process, Pipe
def sender(pipe):
"""
send object to parent on anonymous pipe
"""
pipe.send(['spam'] + [42, 'eggs'])
pipe.close()
def talker(pipe):
"""
send and receive objects on a pipe
"""
pipe.send(dict(name='Bob', spam=42))
reply = pipe.recv()
print('talker got:', reply)
if name == 'main':
(parentEnd, childEnd) = Pipe()
Process(target=sender, args=(childEnd,)).start() # spawn child with pipe
print('parent got:', parentEnd.recv()) # receive from child
parentEnd.close() # or auto-closed on gc
(parentEnd, childEnd) = Pipe()
child = Process(target=talker, args=(childEnd,))
child.start()
print('parent got:', parentEnd.recv()) # receieve from child
parentEnd.send({x * 2 for x in 'spam'}) # send to child
The multiprocessing Module| 249