下面是一个摘自IBM 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)这里的例子运行得很好。我一直在寻找一个稍微不同的修改。这里有一些已知数量的URL,例如5。在for循环中使用range(5)遍历URL并处理它。
如果我只想使用'5‘线程来处理1000个URL,该怎么办?因此,当线程完成时,应将完成的URL从队列中删除,并将新的URL添加到队列中。但所有这些都应该通过使用相同的线程来实现。
我可以查一下,
if self.queue.task_done():
return host这是我检查URL是否成功处理的唯一方法。返回后,我应该从队列中删除URL。并将新的URL添加到队列中。如何使用队列来实现这一点?
谢谢,
发布于 2014-06-06 16:41:56
该代码已经完成了您所描述的工作。如果您将1000个条目放入队列,而不是5个,它们将由相同的5个线程处理-每个线程将从队列中获取一个条目,处理它,然后获取一个新的条目,只要队列中还有条目。
https://stackoverflow.com/questions/24076756
复制相似问题