Python线程代码不代表线程化

时间:2011-02-06 14:42:34

标签: python multithreading

为什么这段代码“行为”没有线程? (请参阅输出。)

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

3 个答案:

答案 0 :(得分: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"

另见:

答案 1 :(得分: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"

答案 2 :(得分:0)

您需要首先启动两个线程,然后在它们都运行时与它们一起加入。