喵喵时光机
在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()