我实现了一个使用 numpy 随机生成器来模拟某些过程的函数。这是此类函数的一个最小示例:
def thread_func(cnt, gen):
s = 0.0
for _ in range(cnt):
s += gen.integers(6)
return s
Run Code Online (Sandbox Code Playgroud)
现在我编写了一个使用python的starmap来调用thread_func的函数。如果我这样写(将相同的 rng 引用传递给所有进程):
from multiprocessing import Pool
import numpy as np
def evaluate(total_cnt, thread_cnt):
gen = np.random.default_rng()
cnt_per_thread = total_cnt // thread_cnt
with Pool(thread_cnt) as p:
vals = p.starmap(thread_func, [(cnt_per_thread,gen) for _ in range(thread_cnt)])
return vals
Run Code Online (Sandbox Code Playgroud)
的结果evaluate(100000, 5)是一个由 5 个相同值组成的数组,例如:
[49870.0, 49870.0, 49870.0, 49870.0, 49870.0]
Run Code Online (Sandbox Code Playgroud)
但是,如果我将不同的 rng 传递给所有进程,例如通过执行以下操作:
vals = p.starmap(thread_func, [(cnt_per_thread,np.random.default_rng()) for _ in range(thread_cnt)])
Run Code Online (Sandbox Code Playgroud)
我得到了预期的结果(5个不同的值),例如:
[49880.0, 49474.0, 50232.0, …Run Code Online (Sandbox Code Playgroud)