系统相关
首页 > 系统相关> > 类函数中获取进程池对象的地址

类函数中获取进程池对象的地址

作者:互联网

类函数获取进程池对象之后,就可以在用pool.apply_async(func…)在类函数里面执行,这个pool要与主进程的命名一致

pool.join()防止主进程在worker结束前结束

pool.close()等待进程池中的worker执行结束后再关闭

from multiprocessing import Pool
from time import sleep
import sys
from test import Tester

if __name__ == “__main__”:
    pool = Pool(5)
    test1 = Tester()
    test1.work()
    test2 = Tester()
    test2.work()
    test3 = Tester()
    test3.work()
    test4 = Tester()
    test4.work()
    test5 = Tester()
    test5.work()
    test6 = Tester()
    test6.work()
    
    pool.close()
    pool.join()
# test.py
import sys
from time import sleep

class Tester:
    def f(self, x):
        for i in range(5):
            print(“%s---%s” % (i, x))
            sleep(1)

    def getPoolObject(self):
        return sys.modules[“__mp_main__”].pool
    
    def work(self):
        pool = self.getPoolObject()
        pool.apply_async(self.f, (5, ))

 

标签:__,函数,Tester,self,work,获取,地址,import,pool
来源: https://www.cnblogs.com/sayiqiu/p/10598218.html