CSJS软件平台开发笔记-python多进程

问题1:multiprocessing模块多进程实现

参考了知乎上的一篇文章python并行计算

apply_async方法

from multiprocessing import Pool

def func(x):
    y = x**2
    return y
def main():
    res = []  # 用于存储func返回值
    a = (6,8,3,4,5)
    p = Pool() # 进程池
    for i in a:
        # 不要在循环中加入.get()去获取返回值,会阻塞进程
        # func的参数只有单个值要加',',默认传入参数为元组
        result = p.apply_async(func, (i,))  
        res.append((i, result))  # 结果聚合
    p.close()
    p.join()
    # 获取函数返回结果
    for i, r in res:
        y = r.get()
        print(str(i) + '的平方是' + str(y))

imap方法

imap方法只支持一个参数,可以把func的输入参数拼成元组再输入,然后在func中进行分离。
tqdm模块可以实现进度条。python多进程中使用tqdm监控任务执行进度

from multiprocessing import Pool
from tqdm import tqdm
def func(params):
    dosomething
    return y1,y2,y3
params = []
for i in range(int(ns)):  # 组成参数元组
    params.append((i, x1, x2, x3))
del i
with Pool() as p:
    res=list(tqdm(p.imap(func, params), total=ns))
p.close()
p.join()
# 获取函数返回值
for sub_res in res:
     res1, res2, res3 = sub_res[0], sub_res[1], sub_res[2]
        

问题2:python打印子进程内容

主进程中quene=Manager().Quene()
子进程中quene.put(message)
zh

问题3:监控进程

可以参考python多进程中使用tqdm监控任务执行进度
tqdm模块可以监控循环体执行进度
from tqdm import tqdm
from time import sleep
for i in tqdm(range(1000)):
sleep(0.01)
显示效果

posted @ 2020-05-25 23:00  Heimdall7  阅读(440)  评论(0)    收藏  举报