from multiprocessing import Pool
class Adder:
"""I'm using this class in place of a monte carlo simulator"""
def add(self, a, b):
return a + b
def setup(x, y, z):
"""Sets up the worker processes of the pool.
Here, x, y, and z would be your global settings. They are only included
as an example of how to pass args to setup. In this program they would
be "some arg", "another" and 2
"""
global adder
adder = Adder()
def job(a, b):
"""wrapper function to start the job in the child process"""
return adder.add(a, b)
if __name__ == "__main__":
args = list(zip(range(10), range(10, 20)))
# args == [(0, 10), (1, 11), ..., (8, 18), (9, 19)]
with Pool(initializer=setup, initargs=["some arg", "another", 2]) as pool:
# runs jobs in parallel and returns when all are complete
results = pool.starmap(job, args)
print(results) # prints [10, 12, ..., 26, 28]
没有测试,但类似的东西应该可以。 数组和锁在进程之间共享。
这里的文档https://docs.python.org/3.5/library/multiprocessing.html有很多示例可以开始
因为您只将状态从子进程返回到父进程,所以使用共享数组和显式锁是过分的。你可以使用
Pool.map
或Pool.starmap
来完成你所需要的。例如:相关问题 更多 >
编程相关推荐