如何使用miltiprocessing进行循环?

时间:2018-07-30 09:23:28

标签: python multiprocessing python-multiprocessing

我试图了解如何实现我的情况下的多处理。 我有两个函数: def all_url() def new_file()。第一个返回包含很多元素的列表。第二个使用此列表进行“ for”循环。我想对第二个功能 new_file()进行多处理,因为从 all_url()返回的列表太大。

代码示例:

def all_url():
   #Here I append elements to urllist
    return urllist

def new_file():
    for each in all_url():
      #There's a lot of code. Each iteration of loop creates a new html file.

new_file()

2 个答案:

答案 0 :(得分:1)

您需要执行以下操作:

from multiprocessing.pool import Pool

def all_url():
    #Here I append elements to urllist
    return urllist

def new_file():
    with Pool() as pool:
        pool.map(new_file_process_url, all_url())

def new_file_process_url(each):
      # Creates html file.

if __name__ == '__main__':
    new_file()

答案 1 :(得分:0)

不确定是否仅因为必须等待生成大量列表而真的需要线程。将differenceInSeconds = difference/1000; 函数定义为生成器,并在需要时调用它。

docker service create --name "testApp" -p 8000:8000 testApp