python中multiprocessing的Pool的用法
介绍
在python的multiprocessing模块中,可以使用Pool类进行多进程任务
用法
import multiprocessing
import time
class Person:
def __init__(self, age):
self.age = age
def myfunc(self, name):
age = self.age
print("Hello my name is " + name)
def job(name, get_name):
time.sleep(10)
return get_name.myfunc(name)
if __name__ == '__main__':
name_list = ['bob', 'tom', 'alice', 'peter', 'angle']
get_name = Person(20)
p = multiprocessing.Pool(4)
start_time = time.time()
for i in name_list:
p.apply_async(job, args=(i,get_name,))
p.close()
p.join()
end_time = time.time()
total_time = end_time - start_time
print(f'All task done! The total time is {total_time:.2f}.')
从输出结果可以看到,程序一共执行了20.07s,表示我们多进程任务执行成功。如果顺序运行,需要花费50s。