第十章:使用进程、线程和协程提供并发性-concurrent.futures:管理并发任务池-进程池

Python进程池ProcessPoolExecutor介绍
博客介绍了Python中ProcessPoolExecutor进程池,其工作与ThreadPoolExecutor类似,但使用进程而非线程,可让CPU密集操作使用单独CPU,避免受全局解释器锁阻塞。还提到要重用工作进程执行多任务,若工作进程出问题,ProcessPoolExecutor会“中断”,BrokenProcessPool异常在处理结果时抛出。

10.6.8 进程池
ProcessPoolExecutor的工作与ThreadPoolExecutor类似,不过使用进程而不是线程。这种方法允许CPU密集的操作使用一个单独的CPU,而不会因为Cpython解释器的全局解释器锁而被阻塞。

from concurrent import futures
import os


def task(n):
    return (n,os.getpid())


ex = futures.ProcessPoolExecutor(max_workers=2)
results = ex.map(task,range(5,0,-1))
for n,pid in results:
    print('ran task {} in process {}'.format(n,pid))

与线程池一样,要重用各个工作进程以执行多个任务。
运行结果:
在这里插入图片描述
如果某个工作进程出了问题,导致它意外退出,则认为ProcessPoolExecutor"中断",不会再调度任务。

from concurrent import futures
import os
import signal


with futures.ProcessPoolExecutor(max_workers=2) as ex:
    print('getting the pid for one worker')
    f1 = ex.submit(os.getpid)
    pid1 = f1.result()

    print('killing process {}'.format(pid1))
    os.kill(pid1,signal.SIGHUP)

    print('submitting another task')
    f2 = ex.submit(os.getpid)
    try:
        pid2 = f2.result()
    except futures.process.BrokenProcessPool as e:
        print('could not start new tasks: {}'.format(e))

BrokenProcessPool异常实际上是在处理结果时抛出的,而不是在提交新任务时抛出。
运行结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值