【问题标题】:python multithreading with list I/O带有列表 I/O 的 python 多线程
【发布时间】: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


【解决方案1】:

您应该为此使用Queue 类。它是一个线程安全的数组。它的“获取”功能从队列中删除项目,重要的是,当没有项目时阻塞并等待其他进程添加它们。 如果您使用multiprocessing,那么您应该使用此模块中的Queue,而不是Queue 模块。 下次您询问有关流程的问题时,请提供您想要的确切 Python 版本。这是 2.6

【讨论】:

  • 谢谢老兄!这至少会给我指明正确的方向!非常感谢
猜你喜欢
  • 2016-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-30
  • 1970-01-01
  • 2012-10-17
  • 2013-03-04
  • 2013-09-27
相关资源
最近更新 更多