由于Global Interpreter Lock带来的影响,python多线程无法实现多核处理器上的并行性,所以需要使用python多进程来实现CPU密集型多任务的并行。
示例代码如下:
import os
from multiprocessing import Pool
import time
def f(x):
y = x * x
time.sleep(2) # 模拟任务执行时间
print("f({})={}".format(x, y))
return y
if __name__ == '__main__':
process_count = os.cpu_count() - 1 # 进程池中的进程数,一般设为cpu数量-1
print("process_count = {}".format(process_count))
p = Pool(process_count) # 创建进程池,其中包含process_count个进程
result_list = []
for i in range(process_count * 3):
result = p.apply_async(f, (i,)) # 向进程池中添加异步任务(非阻塞,可并行执行)
result_list.append(result) # 将结果对象ApplyResult保存到列表中。由于任务执行需要时间,此时的result可能还没有结果值
p.close() # 阻止后续任务提交到进程池
p.join() # 等待进程池内的所有进程结束
# 所有任务都已执行完毕,获取结果
for res in result_list:
print(res.get()) # 使用get来获取apply_async的结果
参考:
https://docs.python.org/zh-cn/3.6/library/multiprocessing.html#module-multiprocessing.pool
https://www.runoob.com/w3cnote/python-single-thread-multi-thread-and-multi-process.html