【发布时间】:2014-05-11 15:42:57
【问题描述】:
我想在 python 中实现多线程,其中线程函数执行一些操作并将 URL 添加到 URL 列表 (links) 并且侦听器从调用脚本中监视 links 列表以获取新元素迭代。使困惑?我也是,我也不知道怎么解释,所以让我尝试用伪代码演示一下:
from multiprocessing import Pool
def worker(links):
#do lots of things with urllib2 including finding elements with BeautifulSoup
#extracting text from those elements and using it to compile the unique URL
#finally, append a url that was gathered in the `lots of things` section to a list
links.append( `http://myUniqueURL.com` ) #this will be unique for each time `worker` is called
links = []
for i in MyBigListOfJunk:
Pool().apply(worker, links)
for link in links:
#do a bunch of stuff with this link including using it to retrieve the html source with urllib2
现在,与其等待所有worker 线程完成并一次性遍历links,有没有办法让我在URL 被附加到links 列表时遍历它们?基本上,生成links 列表的worker 迭代必须与links 本身的迭代分开;但是,与其按顺序运行每个,我希望我可以同时运行它们并节省一些时间......目前我必须在一个循环内调用worker 30-40 次以上,整个脚本大约需要 20 分钟才能完成执行...
非常欢迎任何想法,谢谢。
【问题讨论】:
-
非常简单的生产者/消费者设置应该可以解决问题。此外,您使用的是进程,而不是线程。
标签: python multithreading message-queue