如何使用多处理循环?
How to use miltiprocessing for loop?
我正在尝试了解如何在我的案例中实现多处理。
我有两个函数:def all_url() 和 def new_file()。第一个 returns 一个包含很多元素的列表。第二个使用此列表进行 'for' 循环。我想对第二个函数 new_file() 进行多处理,因为列表 returns 来自 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()
你需要做这样的事情:
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()
不确定您是否真的需要线程,因为您必须等待生成一个巨大的列表。将 all_url
函数定义为生成器,并在需要时调用它。
def all_url():
yield url # not urllist
url = all_url()
def new_file():
current_url = next(url)
# Do the rest
我正在尝试了解如何在我的案例中实现多处理。 我有两个函数:def all_url() 和 def new_file()。第一个 returns 一个包含很多元素的列表。第二个使用此列表进行 'for' 循环。我想对第二个函数 new_file() 进行多处理,因为列表 returns 来自 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()
你需要做这样的事情:
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()
不确定您是否真的需要线程,因为您必须等待生成一个巨大的列表。将 all_url
函数定义为生成器,并在需要时调用它。
def all_url():
yield url # not urllist
url = all_url()
def new_file():
current_url = next(url)
# Do the rest