|
发表于 2018-9-18 17:56:22
|
显示全部楼层
正如其他人所说multiprocessing,只能将Python对象转移到其他的工作进程。如果您无法按照unutbu的描述重新组织代码,则可以使用dills扩展的pickling / unpickling功能来传输数据(尤其是代码数据),如下所示。
此解决方案仅需要安装dill而不需要其他库pathos:
- import os
- from multiprocessing import Pool
- import dill
- def run_dill_encoded(payload):
- fun, args = dill.loads(payload)
- return fun(*args)
- def apply_async(pool, fun, args):
- payload = dill.dumps((fun, args))
- return pool.apply_async(run_dill_encoded, (payload,))
- if __name__ == "__main__":
- pool = Pool(processes=5)
- # asyn execution of lambda
- jobs = []
- for i in range(10):
- job = apply_async(pool, lambda a, b: (a, b, a * b), (i, i + 1))
- jobs.append(job)
- for job in jobs:
- print job.get()
- print
- # async execution of static method
- class O(object):
- @staticmethod
- def calc():
- return os.getpid()
- jobs = []
- for i in range(10):
- job = apply_async(pool, O.calc, ())
- jobs.append(job)
- for job in jobs:
- print job.get()
复制代码 |
|