def whoami(label, lock):
msg = '%s: name:%s, pid:%s'
with lock:
print(msg % (label, name, os.getpid()))
if name == 'main':
lock = Lock()
whoami('function call', lock)
p = Process(target=whoami, args=('spawned child', lock))
p.start()
p.join()
for i in range(5):
Process(target=whoami, args=(('run process %s' % i), lock)).start()
with lock:
print('Main process exit.')
When run, this script first calls a function directly and in-process; then launches a call
to that function in a new process and waits for it to exit; and finally spawns five function
call processes in parallel in a loop—all using an API identical to that of the
threading.Thread model we studied earlier in this chapter. Here’s this script’s output
on Windows; notice how the five child processes spawned at the end of this script
outlive their parent, as is the usual case for processes:
C:\...\PP4E\System\Processes> multi1.py
function call: name:__main__, pid:8752
spawned child: name:__main__, pid:9268
Main process exit.
run process 3: name:__main__, pid:9296
run process 1: name:__main__, pid:8792
run process 4: name:__main__, pid:2224
run process 2: name:__main__, pid:8716
run process 0: name:__main__, pid:6936
Just like the threading.Thread class we met earlier, the multiprocessing.Process object
can either be passed a target with arguments (as done here) or subclassed to redefine
its run action method. Its start method invokes its run method in a new process, and
the default run simply calls the passed-in target. Also like threading, a join method
waits for child process exit, and a Lock object is provided as one of a handful of process
synchronization tools; it’s used here to ensure that prints don’t overlap among pro-
cesses on platforms where this might matter (it may not on Windows).
Implementation and usage rules
Technically, to achieve its portability, this module currently works by selecting from
platform-specific alternatives:
- On Unix, it forks a new child process and invokes the Process object’s run method
in the new child.
246 | Chapter 5: Parallel System Tools