既然你只能從子進程返回狀態的父進程,然後使用一個共享的陣列,並且明確地鎖是矯枉過正。您可以使用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