""" thread_demo.py $ python3 thread_example.py main - starting thread1 main - starting thread2 main - sleep 10 one - 1 two - 1 two - 2 two - 3 two - 4 one - 2 two - 5 one - 3 one - 4 one - 5 See https://docs.python.org/3/library/_thread.html Jim Mahoney | cs.marlboro.college | MIT License | April 2018 """ from _thread import start_new_thread from time import sleep def print_numbers(name, wait_sec, max=5): """ print ' - ' from 1 to max with a delay between lines """ for i in range(1, max+1): print(" {} - {}".format(name, i)) sleep(wait_sec) def main(): # spawn the first thread - it starts running "in parallel" print("main - starting thread1") thread1 = start_new_thread(print_numbers, ('one', 1.1)) # spawn the second thread - it also starts running "in parallel" print("main - starting thread2") thread2 = start_new_thread(print_numbers, ('two', 0.3)) # don't quit before the threads have time to run. print("main - sleeping for 10 sec.") sleep(10) # bye! print("main - exit.") if __name__ == '__main__': main()