# CS 450; Python Thread list example # version 2014-01-31 8:37 PM # # Create a list of threads, start them all, then join them all # from threading import Thread 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)) # main(nbr_thds) creates a number of threads (default of 5) # then it starts all the threads, and then it waits until they all finish. # Each thread sleeps for a random number of seconds >= 1 and <= 9), # def main(nbr_thds = 5): # ts is a list of thread objects ts = [Thread(target=say_hello, args=([i, random.randint(1,9)])) for i in range(nbr_thds)] for t in ts: t.start() print('Started thread {}'.format(t.ident)) # note: ident field for t in ts: t.join() print('Joined thread {}'.format(t.ident)) main()