[英]Python threaded code not acting threaded
為什么此代碼“操作”未穿線? (請參閱輸出。)
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
說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"
也可以看看:
您的線程連接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"
您需要先啟動兩個線程,然后在它們都運行后再加入它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.