我对Python中的多进程编程还不太熟悉,现在我想要尝试以下内容:
import os
from multiprocessing import Pool
from random import randint
def example_function(a):
new_numbers = [randint(1, a) for i in range(0, 50)]
with Pool(processes=os.cpu_count()-1) as pool:
results = pool.map(str, new_numbers)
return results
if __name__ == '__main__':
numbers = [randint(1, 50) for i in range(0, 50)]
with Pool(processes=os.cpu_count()) as pool:
results = pool.map(example_function, numbers)
print("Final results:", results)
然而,当我运行时出现了以下错误:"AssertionError: daemonic processes are not allowed to have children"。
将
pool.map
替换为for循环可以使其正常工作。例如,对于第二个:results = []
for n in numbers:
results.append(example_function(n))
然而,由于外部和内部任务都非常密集,我希望能够并行执行两者。我该怎么做?