1import threading
2
3def worker(argument):
4 print(argument)
5 return
6
7for i in range(5):
8 t = threading.Thread(target=worker, args=[i])
9 t.start()
1import threading
2import time
3
4def thread_function(name):
5 print(f"Thread {name}: starting")
6 time.sleep(2)
7 print(f"Thread {name}: finishing")
8
9my_thread = threading.Thread(target=thread_function, args=(1,))
10my_thread.start()
11time.sleep(1)
12my_second_thread = threading.Thread(target=thread_function, args=(2,))
13my_second_thread.start()
14my_second_thread.join() # Wait until thread finishes to exit
1import threading
2from random import randint
3from time import sleep
4
5
6def print_number(number):
7
8 # Sleeps a random 1 to 10 seconds
9 rand_int_var = randint(1, 10)
10 sleep(rand_int_var)
11 print "Thread " + str(number) + " slept for " + str(rand_int_var) + " seconds"
12
13thread_list = []
14
15for i in range(1, 10):
16
17 # Instantiates the thread
18 # (i) does not make a sequence, so (i,)
19 t = threading.Thread(target=print_number, args=(i,))
20 # Sticks the thread in a list so that it remains accessible
21 thread_list.append(t)
22
23# Starts threads
24for thread in thread_list:
25 thread.start()
26
27# This blocks the calling thread until the thread whose join() method is called is terminated.
28# From http://docs.python.org/2/library/threading.html#thread-objects
29for thread in thread_list:
30 thread.join()
31
32# Demonstrates that the main process waited for threads to complete
33print "Done"
34