python的多进程编程(2)

本文详细介绍了Python的multiprocessing库中的Pool类,包括如何使用进程池执行任务,以及Pool的主要方法如apply、map等。同时,强调了Pool只能在__main__模块中使用,否则会在交互式解释器中遇到问题。此外,还概述了Process类的关键属性和方法,如run、start、join等,并提及了进程的守护进程标志daemon及其注意事项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 继续翻译python的multiprocess,开发环境我就不再说了,(1)中有交代,闲话休提,直接上正文
16.6.1.5 Using a pool of workers(使用辅助进程池)

Pool类是辅助进程池。它有一些方法,可以让任务以多种方式分配给辅助进程。
例如:

from multiprocessing import Pool


def f(x):
    return x * x

if __name__ == '__main__':
    pool = Pool(processes=4)  # 创建4个辅助进程
    result = pool.apply_async(f, [10])  # 异步计算"f(10)"
    print result.get(timeout=1)  # 打印"100",除非你电脑*特别*慢
    print pool.map(f, range(10))  # 打印 "[0, 1, 4,..., 81]"

注意:只有pool创建的进程才能使用pool的方法

注意:这个包里的功能需要有__main__模块。在Progarmming guidelines里有介绍,但是这里很有必要强调。这意味着,有些例子,就像Pool,在交互性解释器里无法工作。例如:

>>> from multiprocessing import Pool
>>> p = Pool(5)
>>> def f(x):
...     return x*x
...
>>> p.map(f, [1,2,3])
Process PoolWorker-1:
Process PoolWorker-2:
Process PoolWorker-3:
Traceback (most recent call last):
AttributeError: 'module' object has no attribute 'f'
AttributeError: 'module' object has no attribute 'f'
AttributeError: 'module' object has no attribute 'f'

(如果你试着这样写,会随机输出3个异常信息,你必须想办法停止主进程)

16.6.2 参考

multiprocessing包河threading模块的大部分API是一样的

16.6.2.1 进程和异常

class multiprocessing.Process(group=None,target=None,name=None,args=(),kwargs={})
Process对象表示他在一个单独的进程里运行。Process class有和threading.Thread一样的方法。
在创建Process时,构造器应该含有关键字参数。group应该总是None;它存在的唯一意思是和threading.Thread兼容。target是一个可调用对象,通过run()方法调用。它默认是None,即什么都不做。name是进程的名字。默认情况下,进程的唯一名称是这样的:
Process-N1:N2:…:Nk‘, N1,N2……Nk是整数序列,整数的长度由进程决定。args是target方法的参数元组。kwargs是target的关键字参数字典。默认情况下,不传任何参数给target.
如果子类重写了process的构造器,在进程中添加任何方法前,必须调用基类构造器(Process.__init__())
run()
表示进程的活动方法
你可以在子类中重写此方法。 The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.
start()
开启进程的活动方法
每个进程必须至少调用这个方法一次。它在一个单独的进程中启用对象的run()方法。
join([timeout])
阻塞主进程,直到开启了join()方法的进程结束或超时
如果timeout 是None就没有超时
一个进程可以使用join()方法多次
一个进程不能join它自身,因为这回造成死锁(deadlock)。在一个进程start前join是错误的。
name
进程的名字
名字是string,只用作唯一标识。它没有任何意义。多个进程有相同的name,构造器会初始化name。
is_alive()
返回进程是否alive
一般情况下,一个进程对象从start()开始直到子进程结束都是alive的
daemon
进程的守护进程标识,一个布尔值。必须在start()方法前设置。
它的初始值继承自创建它的进程
当一个进程退出时,它的所有子守护进程会结束
注意:守护进程不能创建子进程。Otherwise a daemonic process would leave its children orphaned if it gets terminated when its parent process exits. Additionally, these are not Unix daemons or services, they are normal processes that will be terminated (and not joined) if non-daemonic processes have exited。

除了threading.Thread的API,Process对象还提供了下面的属性和方法:
pid
return进程的ID.进程产生前,它是None
exitcode
子进程的退出代码。如果进程还没有结束,这个值是None.A negative value -N indicates that the child was terminated by signal N.
authkey
进程的身份标识key(字节字符串)
当multiprocessing初始化,主进程会被赋值一个随机字符串(os.urandom())
当进程对象被创建,它会继承父进程的身份标识key,虽然这个值可以通过设置authkey来改变
查看Authentication keys.
terminate()
结束进程。Unix使用终止信号。Windows使用TerminateProcess()。 Note that exit handlers and finally clauses, etc., will not be executed。
警告:If this method is used when the associated process is using a pipe or queue then the pipe or queue is liable to become corrupted and may become unusable by other process. Similarly, if the process has acquired a lock or semaphore etc. then terminating it is liable to cause other processes to deadlock.
注意:start(),join(),is_alive(),terminate()和exitcode方法只能由创建进程的对象调用
一些Process的方法的使用的例子:

>>> import multiprocessing, time, signal
>>> p = multiprocessing.Process(target=time.sleep, args=(1000,))
>>> print p, p.is_alive()
<Process(Process-1, initial)> False
>>> p.start()
>>> print p, p.is_alive()
<Process(Process-1, started)> True
>>> p.terminate()
>>> time.sleep(0.1)
>>> print p, p.is_alive()
<Process(Process-1, stopped[SIGTERM])> False
>>> p.exitcode == -signal.SIGTERM
True

exception multiporcessing.BufferTooShort
当Connection.recv_bytes_into()方法时,如果提供的buffer对象太小,会抛出这个异常
如果e是BufferTooShort的实例,e.args[0]会提供以byte string形式的信息。

今天就到这里,如果有错误,纰漏和需要改进的地方,请不吝指正。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值