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...
That's perfectly normal. You're not waiting for the threads to finish, so there is no reason for your code to block after the for
loop.
You'll need a second loop in which you call .join()
on each thread if you want to wait for them.
Yet, 'end of script' gets printed right after I execute the first thread, instead of after all the threads have completed
That's only the impression you get. Run that code a few hundred times and you could see the 'end of script' before any thread output at all, or after two or three threads have logged. That 'end of script' is printed once all the threads have been started.
As soon you start a thread it competes with the other ones (including your main thread) for resources like the CPU. Which thread gets to run is decided by the operating system and (generally) not under your control, and not predictable either.
So in the output you posted, the first thread got a bit of CPU while the main thread was still busy starting the other ones. That's just a "coincidence".
You want to add .join()
, since by default there's no reason for your main program to block until the threads are finished:
my_threads = []
for i in range(3):
my_thread = MyThread()
my_thread.name = i
my_thread.start()
my_threads.append(my_thread)
for t in my_threads:
t.join()
print 'end of script'
Keep track of your thread objects, and call join()
on the object to wait for the threads to complete before printing end of script
.
精彩评论