from threading import Thread
import time
print 'start of script'
class MyThread(Thread):
def run(self):
for i in xrange(10):
print 'thread->', '['+self.name+']', '('+str(i)+')'
time.sleep(2)
for i in range(3):
my_thread = MyThread()
my_thread.name = i
my_thread.start()
print 'end of script'
>>> ================================ RESTART ================================
>>>
start of script
thread->thread->thread->end of script
[0][1][2]
>>> (0)(0)(0)
thread->thread->thread-> [0][2][1] (1)(1)(1)
thread->thread-> thread-> [0] [2] [1] (2) (2)
(2)
thread-> thread->thread->[0] [2][1](3)
(3)(3)
thread-> thread->thread->[0] [2][1](4)
(4)(4)
thread-> thread->[0]thread-> [2](5)[1]
(5)(5)
thread-> [0]thread->thread-> (6)[2][1]
(6)(6)
thread-> thread->[0]thread-> [2](7)[1]
(7)(7)
thread-> thread->[0] thread-> [2] (8) [1]
(8)
(8)
thread->thread-> thread-> [0] [2] [1] (9) (9)
(9)
>>>
As you can see I’m printing ‘start of script’ first, then executing multiple threads, and then printing ‘end of script’
Yet, ‘end of script’ gets printed right after I execute the first thread, instead of after all the threads have completed. How can I prevent this?
The jumbled nature of the output is expected and in fact desired as these threads are supposed to be executing simultaneously…
I’m on Windows 7 python 2.7 btw…
You want to add
.join(), since by default there’s no reason for your main program to block until the threads are finished: