Python的multiprocessing.Pool类提供了多种方法来分发任务给进程池中的工作进程。这些方法在功能和用途上有所不同,适用于不同的场景。以下是multiprocessing.Pool中八个主要函数的对比
以下是multiprocessing.Pool中每个函数的示例:
from multiprocessing import Pool
def square(x):
return x * x
if __name__ == '__main__':
with Pool(4) as p:
result = p.apply(square, (10,))
print(result)
from multiprocessing import Pool
def square(x):
return x * x
def print_result(result):
print(result)
if __name__ == '__main__':
with Pool(4) as p:
result = p.apply_async(square, (10,), callback=print_result)
result.wait() # 等待任务完成
from multiprocessing import Pool
def square(x):
return x * x
if __name__ == '__main__':
with Pool(4) as p:
results = p.map(square, range(10))
print(results)
from multiprocessing import Pool
def square(x):
return x * x
def print_result(result):
print(result)
if __name__ == '__main__':
with Pool(4) as p:
result = p.map_async(square, range(10), callback=print_result)
result.wait() # 等待所有任务完成
from multiprocessing import Pool
def multiply(x, y):
return x * y
if __name__ == '__main__':
with Pool(4) as p:
results = p.starmap(multiply, [(1, 2), (2, 3), (3, 4)])
print(results)
from multiprocessing import Pool
def multiply(x, y):
return x * y
def print_result(result):
print(result)
if __name__ == '__main__':
with Pool(4) as p:
result = p.starmap_async(multiply, [(1, 2), (2, 3), (3, 4)], callback=print_result)
result.wait() # 等待所有任务完成
from multiprocessing import Pool
def square(x):
return x * x
if __name__ == '__main__':
with Pool(4) as p:
for result in p.imap(square, range(10)):
print(result)
from multiprocessing import Pool
def square(x):
return x * x
if __name__ == '__main__':
with Pool(4) as p:
for result in p.imap_unordered(square, range(10)):
print(result)