2011-06-12 58 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

相關問題