I'm trying to fix seed while using pool.imap:
import numpy as np
import random
import time
import multiprocessing
from multiprocessing.pool import ThreadPool
np.random.seed(2019)
N = 10
def print_fn(i):
time.sleep(random.randint(1,2)) # Emulate some work
print(i, ':', np.random.uniform(-1.0, 1.0))
def f1():
for i in range(N):
print_fn(i)
def f2():
n_threads = max(min(multiprocessing.cpu_count(), N), 1)
pool = ThreadPool(n_threads)
for _ in pool.imap(print_fn, range(N)):
pass
pool.close()
pool.join()
#f1()
f2()
Results of f1() are the same across runs:
run1:
0 : 0.8069644288385487
1 : -0.21383898669951495
2 : 0.2479399225955068
3 : 0.27575480204445313
4 : 0.7609981375565242
5 : -0.401655961209485
6 : 0.40439654037310335
7 : 0.8064123226444868
8 : 0.7627638529632341
9 : -0.18850040404017343
run2:
0 : 0.8069644288385487
1 : -0.21383898669951495
2 : 0.2479399225955068
3 : 0.27575480204445313
4 : 0.7609981375565242
5 : -0.401655961209485
6 : 0.40439654037310335
7 : 0.8064123226444868
8 : 0.7627638529632341
9 : -0.18850040404017343
Results of f2() are not the same across runs:
run1:
0 : 0.8069644288385487
2 : -0.21383898669951495
6 : 0.2479399225955068
8 : 0.27575480204445313
1 : 0.7609981375565242
4 : -0.401655961209485
3 : 0.40439654037310335
5 : 0.8064123226444868
9 : 0.7627638529632341
7 : -0.18850040404017343
run2:
0 : 0.8069644288385487
5 : -0.21383898669951495
2 : 0.2479399225955068
3 : 0.27575480204445313
1 : 0.7609981375565242
4 : -0.401655961209485
6 : 0.40439654037310335
8 : 0.8064123226444868
7 : 0.7627638529632341
9 : -0.18850040404017343
How to fix this?
Aucun commentaire:
Enregistrer un commentaire