# CS 450; Thread example 4: Create threads in python # version 2014-01-26 11:27 AM # import threading from threading import Thread import time def main(): print("Start threads but don't join them\n") for i in range(5): # Create a thread that sleeps for 6-i sec thd = Thread(target=say_hello, \ args=(6-i,), \ name="mythread_" + str(i)) thd.start() print('starting {}'.format(thd.name) ) print('{} alive? {}'\ .format(thd.name, thd.is_alive()) ) def say_hello(sleep_seconds): myname = threading.current_thread().name print('hello from {}'.format(myname)) time.sleep(sleep_seconds) print('goodbye from {}'.format(myname)) main() # run the main program # Sample output: # # hello from mythread_0 # starting mythread_0 # mythread_0 alive? True # hello from mythread_1 # starting mythread_1 # mythread_1 alive? True # hello from mythread_2 # starting mythread_2 # mythread_2 alive? True # hello from mythread_3 # starting mythread_3 # mythread_3 alive? True # hello from mythread_4 # starting mythread_4 # mythread_4 alive? True # goodbye from mythread_4 # goodbye from mythread_3 # goodbye from mythread_2 # goodbye from mythread_1 # goodbye from mythread_0