带有列表I / O的python多线程

时间:2014-04-01 03:21:08

标签: python multithreading message-queue

我想在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,因为它们被附加到{ {1}}列表?基本上,links迭代生成worker列表HAS与links本身的迭代分开;然而,不是每次顺序运行我希望我可以同时运行它们并节省一些时间......目前我必须在循环内调用links超过30-40次,整个脚本大约需要20分钟到完成执行...

非常欢迎任何想法,谢谢。

1 个答案:

答案 0 :(得分:1)

您应该使用Queue类。它是一个线程安全的数组。它得到了'函数从队列中删除项目,并且,重要的是,在没有项目时阻止,并等待其他进程添加它们。 如果您使用multiprocessing,则应使用此模块中的Queue,而不是Queue模块。 下次您询问有关流程的问题时,请提供您想要的精确Python版本。这是2.6