python守护进程进程池_Python进程池非守护进程?

喵喵时光机

在multiprocessing.pool.Pool类创建在其工作进程__init__的方法,使他们邪,开始他们,这是不可能自己重新设置daemon属性False在开始之前(事后这是不允许的了)。但是,您可以创建自己的multiprocesing.pool.Pool(multiprocessing.Pool只是包装函数)multiprocessing.Process子类,并替换您自己的子类(该子类通常是非守护程序的)用于工作进程。这是如何执行此操作的完整示例。重要的部分是两个类NoDaemonProcess,MyPool在顶部,在最后pool.close(),pool.join()在您的MyPool实例上调用和。#!/usr/bin/env python# -*- coding: UTF-8 -*-import multiprocessing# We must import this explicitly, it is not imported by the top-level# multiprocessing module.import multiprocessing.poolimport timefrom random import randintclass NoDaemonProcess(multiprocessing.Process):    # make 'daemon' attribute always return False    def _get_daemon(self):        return False    def _set_daemon(self, value):        pass    daemon = property(_get_daemon, _set_daemon)# We sub-class multiprocessing.pool.Pool instead of multiprocessing.Pool# because the latter is only a wrapper function, not a proper class.class MyPool(multiprocessing.pool.Pool):    Process = NoDaemonProcessdef sleepawhile(t):    print("Sleeping %i seconds..." % t)    time.sleep(t)    return tdef work(num_procs):    print("Creating %i (daemon) workers and jobs in child." % num_procs)    pool = multiprocessing.Pool(num_procs)    result = pool.map(sleepawhile,        [randint(1, 5) for x in range(num_procs)])    # The following is not really needed, since the (daemon) workers of the    # child's pool are killed when the child is terminated, but it's good    # practice to cleanup after ourselves anyway.    pool.close()    pool.join()    return resultdef test():    print("Creating 5 (non-daemon) workers and jobs in main process.")    pool = MyPool(5)    result = pool.map(work, [randint(1, 5) for x in range(5)])    pool.close()    pool.join()    print(result)if __name__ == '__main__':    test()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值