python开发cs软件_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)

显示效果

1545619-20200426101650818-509630324.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值