[英]Why is infinite loop needed when using threading and a queue in Python
我正在嘗試理解如何使用線程,我在http://www.ibm.com/developerworks/aix/library/au-threadingpython/上看到了這個很好的例子。
#!/usr/bin/env python
import Queue
import threading
import urllib2
import time
hosts = ["http://yahoo.com", "http://google.com", "http://amazon.com",
"http://ibm.com", "http://apple.com"]
queue = Queue.Queue()
class ThreadUrl(threading.Thread):
"""Threaded Url Grab"""
def __init__(self, queue):
threading.Thread.__init__(self)
self.queue = queue
def run(self):
while True:
#grabs host from queue
host = self.queue.get()
#grabs urls of hosts and prints first 1024 bytes of page
url = urllib2.urlopen(host)
print url.read(1024)
#signals to queue job is done
self.queue.task_done()
start = time.time()
def main():
#spawn a pool of threads, and pass them queue instance
for i in range(5):
t = ThreadUrl(queue)
t.setDaemon(True)
t.start()
#populate queue with data
for host in hosts:
queue.put(host)
#wait on the queue until everything has been processed
queue.join()
main()
print "Elapsed Time: %s" % (time.time() - start)
我不明白的部分是run
方法有無限循環的原因:
def run(self):
while True:
... etc ...
只是為了笑,我沒有循環運行程序,看起來它運行正常! 那么有人可以解釋為什么需要這個循環嗎? 由於沒有break語句,循環如何退出?
你想讓線程執行多個工作嗎? 如果沒有,您不需要循環。 如果是這樣,你需要一些能夠做到這一點的東西。 循環是一種常見的解決方案。 您的示例數據包含五個作業,程序啟動五個線程。 所以,你不需要任何線程在這里做一個以上的作業。 但是,請嘗試向工作負載添加一個URL,並查看更改內容。
循環是必需的,因為沒有它,每個工作線程一完成第一個任務就會終止。 你想要的是讓工人完成另一項任務。
在上面的代碼中,您創建了5個工作線程,這恰好足以覆蓋您正在使用的5個URL。 如果你有> 5個URL,你會發現只有前5個被處理過。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.