# CS 450; Python Process list example # version 2014-02-09 3:58 PM # # Create a list of processes, start them all, then join them all # from multiprocessing import Process import time # for sleep import random # say_hello prints its id and sleeps for a given nbr of seconds # def say_hello(id, seconds): print('Child {} is running'.format(id)) time.sleep(seconds) print('Child {} is done'.format(id)) def say_hello2(id): print('Child {} is running'.format(id)) time.sleep(random.randint(0, 3)) print('Child {} is done'.format(id)) # main(nbr_procs) creates a number of procs (default of 5) # then it starts all the processes, and then it waits until they all finish. # Each process sleeps for a random number of seconds >= 1 and <= 9), # def main(nbr_procs = 5): # ps is a list of process objects ps = [Process(target=say_hello, args=([i, random.randint(1,9)])) for i in range(nbr_procs)] for p in ps: p.start() print('Started process {}'.format(p.pid)) # note: pid field for p in ps: p.join() print('Joined process {}'.format(p.pid)) # main()