既然你只能从子进程返回状态的父进程,然后使用一个共享的阵列,并且明确地锁是矫枉过正。您可以使用Pool.map
或Pool.starmap
来完成您需要的功能。例如:
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]
如果你搜索一些答案,你有大量的示例代码。 因此,如果你不提供你的一些,我们将无法帮助你。 顺便说一下,使用[semaphores](https://docs.python.org/2/library/threading.html#semaphore-objects)来锁定线程 – Raskayu
关于[示例]有什么不清楚的地方(https://docs.python .org/3/library/multiprocessing.html#sharing-state-between-processes)在官方文档中? – mata
您在模拟进行中时是否需要访问阵列?如果没有,你可以使用一组'Pool.map'函数。 – Dunes