类函数获取进程池对象之后,就可以在用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, ))