2011-02-06 78 views
0

爲什麼此代碼沒有「行爲」線程化? (請參閱輸出)。Python線程代碼不起作用線程

import time 
from threading import Thread 

def main(): 
    for nums in [range(0,5), range(5,10)]: 
     t = Spider(nums) 
     t.start() 
     print 'started a thread' 
     t.join() 
    print "done" 

class Spider(Thread): 
    def __init__(self, nums): 
     Thread.__init__(self) 
     self.nums = nums 
    def run(self): # this is an override 
     for num in self.nums: 
      time.sleep(3) # or do something that takes a while 
      print 'finished %s' % (num,) 

if __name__ == '__main__': 
    main() 

輸出:

started a thread 
finished 0 
finished 1 
finished 2 
finished 3 
finished 4 
started a thread 
finished 5 
finished 6 
finished 7 
finished 8 
finished 9 
done 

回答

6

當你說t.join(),你告訴它等待線程結束。

這意味着,您要求它創建一個線程,啓動它,然後等待線程結束後再創建一個新線程。

如果您希望它執行多線程操作,您需要將join()移到循環外部。

def main(): 
    # We will store the running threads in this 
    threads = [] 
    # Start the threads 
    for nums in [range(0,5), range(5,10)]: 
     t = Spider(nums) 
     t.start() 
     print 'started a thread' 
     threads.append(t) 
    # All the threads have been started 
    # Now we wait for them to finish 
    for t in threads: 
     t.join() 
    print "done" 

參見:

+0

因此,您可能希望將線程引用存儲在列表中,並將它們連接到循環之外。 – 2011-02-06 14:46:12

0

您需要先啓動兩個線程,然後和他們在一起,一旦他們都在運行。

1

您的主題加入t.join會阻塞主線程,直到線程完成執行(http://docs.python.org/library/threading.html#threading.Thread.join)。將代碼更改爲如下所示:

def main(): 
    threads = [] 
    for nums in [range(0,5), range(5,10)]: 
    t = Spider(nums) 
    t.start() 
    print 'started a thread' 
    threads.append(t) 
    for t in threads: t.join() 
    print "done" 
+0

`對於t中的線程:t.join()`不再需要輸入,並且不會創建不必要的Nones列表 – 2011-02-07 01:02:12