August 2018
Intermediate to advanced
366 pages
10h 14m
English
Pretty much like in the ThreadPool recipe, we will need two functions that will act as our tasks running concurrently in the processes.
In the case of processes, we don't need to perform I/O actually to run concurrently, so our tasks could be doing anything. What I'm going to use is the computing of the Fibonacci series while printing out progress, so that we can see how the output of the two processes will interleave:
import os
def fib(n, seen):
if n not in seen and n % 5 == 0:
# Print out only numbers we didn't yet compute
print(os.getpid(), '->', n)
seen.add(n)
if n < 2:
return n
return fib(n-2, seen) + fib(n-1, seen)
So, now we need to create the multiprocessing Pool that will run the fib function and spawn computation: ...