2011-06-12 42 views
2
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) 


>>> 

正如你可以看到我打印的“脚本的开始”,然后再执行多个线程,然后打印线程早期执行后的代码,为什么?

“脚本结束”不过,“脚本结束”被印我执行之后第一个线程,而不是在所有线程完成之后。我怎样才能防止这一点?

输出的混乱性质预期,实际上希望作为这些线程都应该是同时执行...

我在Windows 7是蟒蛇2.7 BTW ...

回答

5

你想添加.join(),因为在默认情况下,我们没有理由对你的主程序阻塞,直到线程完成:

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' 
+0

线程技术上何时开始执行?是不是当你调用.start(),但在你的例子中,它似乎只有当你调用.join()所有那些你已经“.start() - ed”我很困惑...... – MistahX 2011-06-12 17:11:39

+0

一旦你调用start,线程就开始执行。它们与原始代码并行运行;连接调用只是确保它们在连接返回之前完成。 – Amber 2011-06-12 19:11:53

1

保持你的线程对象的跟踪,并调用join()对象上等待的线程在打印之前完成end of script

7

这很正常。您不必等待线程完成,因此在for循环之后没有任何理由阻止您的代码。

如果您想等待它们,您需要在每个线程中调用.join()的第二个循环。

不过,“脚本结束”被印刷之后我执行的第一线,而不是在所有的线程都完成

这只是你得到的印象。运行该代码几百次,在任何线程输出之前或者在两个或三个线程已经记录之前,您可以看到“脚本结束”。 所有线程启动后,将打印'脚本结束'。

只要你启动一个线程,它就会与其他CPU(包括你的主线程)竞争CPU资源。哪个线程可以运行取决于操作系统,并且(通常)不受您的控制,也不可预测。

所以在你发布的输出中,第一个线程得到了一点CPU,而主线程仍然忙着开始其他线程。这只是一个“巧合”。

+0

+1提到为什么这是预期的。 OP似乎需要它。 – delnan 2011-06-12 16:53:37

+0

是的,很好的解释。 :) – MistahX 2011-06-12 17:17:13

相关问题