# CS 450; Python Process pool example # version 2014-01-31 8:37 PM # # Create a pool of processes; then create a number of # processes and run them from the pool. # from multiprocessing import Pool import os, random, time # This time, say hello prints out the id and returns # its process id. To make it easier (?) to read the # output, the messages about the child running / # finishing have >'s prepended when we start and <'s # when we finish. # def say_hello(id): print(id*'>' + ' Child {} is running'.format(id)) time.sleep(1/random.randint(1,9)) print(id*'<' + ' Child {} is finished'.format(id)) return os.getpid() # Create a number of say hello processes and run them # using the pool of available processes. We print # out a list of the process ids used. Note the number # of distinct process ids = poolsize. # def main(poolsize=2, nbr_procs=8): pool = Pool(processes = poolsize); print(pool.map(say_hello, range(nbr_procs))) pool.close() # Start cleanup pool.join() # Wait for cleanup to finish main()