我在 Python 中使用多处理库时遇到了困难,我想在其中使用 Pool。
我有示例代码来演示我的问题(实际代码要复杂得多,但在演示示例中没有帮助)
代码:
def Multicore_Patterns_List_processor(Variable1, Variable2, Variable3):
print(f"Variable1 = {Variable1}, Variable2 = {Variable2}, Variable3 = {Variable3}, current pattern is {Pattern}")
Variable1 = 1
Variable2 = 2
Variable3 = 3
MultiCores = 3
Paterns_list = list(range(1, 21))
with Pool(processes=MultiCores) as pool:
pool.imap(Multicore_Patterns_List_processor(Variable1=Variable1, Variable2=Variable2, Variable3=Variable3), Paterns_list)
代码应该做什么:
感谢您的帮助
扬·瓦什科
期望函数的每个处理都将使用变量以及用于多重处理的迭代器。
有多种方法可以实现您的目标。如果你想使用 imap() 那么你可以这样做:
from multiprocessing import Pool
def Multicore_Patterns_List_processor(args):
Variable1, Variable2, Variable3, Pattern = args
print(f"{Variable1=}, {Variable2=}, {Variable3=}, current pattern is {Pattern}")
def genargs(Variable1, Variable2, Variable3):
for p in range(10):
yield Variable1, Variable2, Variable3, p
if __name__ == "__main__":
Variable1 = 1
Variable2 = 2
Variable3 = 3
MultiCores = 3
with Pool(processes=MultiCores) as pool:
pool.imap(Multicore_Patterns_List_processor, genargs(Variable1, Variable2, Variable3))
pool.close()
pool.join()
输出:
Variable1=1, Variable2=2, Variable3=3, current pattern is 0
Variable1=1, Variable2=2, Variable3=3, current pattern is 1
Variable1=1, Variable2=2, Variable3=3, current pattern is 2
Variable1=1, Variable2=2, Variable3=3, current pattern is 3
Variable1=1, Variable2=2, Variable3=3, current pattern is 4
Variable1=1, Variable2=2, Variable3=3, current pattern is 5
Variable1=1, Variable2=2, Variable3=3, current pattern is 6
Variable1=1, Variable2=2, Variable3=3, current pattern is 7
Variable1=1, Variable2=2, Variable3=3, current pattern is 8
Variable1=1, Variable2=2, Variable3=3, current pattern is 9