I want to make each process produce random numbers but I want them be reproducible across runs.
Here is example code:
import random
from multiprocessing import Process
random.seed(2019)
def f2():
print('from f2:')
v = random.randint(0, 10)
a = random.randint(0, 10)
print('v:', v)
return v, a
def python_process_test():
n_workers = 2
workers = []
for i in range(n_workers):
p = Process(target=f2, args=())
p.start()
workers.append(p)
for p in workers:
p.join()
if __name__ == '__main__':
python_process_test()
This is not desired behaviour, because values are not the same across runs:
run 1:
from f2:
v: 6
from f2:
v: 4
run 2:
from f2:
v: 0
from f2:
v: 5
UPDATE:
import time
import random
from multiprocessing import Process
random.seed(2019)
def get_random_sleep_time_v1():
return random.randint(0,3)
def get_random_sleep_time_v2():
from datetime import datetime
random.seed(datetime.now())
return random.randint(0,3)
def f2(rnd_seed, process_id):
random.seed(rnd_seed)
# To rundomize order in which process will print
sleep_time = get_random_sleep_time_v1()
#sleep_time = get_random_sleep_time_v2()
time.sleep(sleep_time)
print('process_id:', process_id)
v = random.randint(0, 10)
a = random.randint(0, 10)
print('v:', v)
return v, a
def python_process_test():
n_workers = 4
workers = []
for i in range(n_workers):
rnd_seed = random.randint(0,10)
p = Process(target=f2, args=(rnd_seed,i))
p.start()
workers.append(p)
for p in workers:
p.join()
if __name__ == '__main__':
python_process_test()
Using get_random_sleep_time_v1
I get desired behaviour but order of processes not changing from run to run:
run 1:
process_id: 0
v: 1
process_id: 3
v: 1
process_id: 1
v: 9
process_id: 2
v: 2
run 2:
process_id: 0
v: 1
process_id: 3
v: 1
process_id: 1
v: 9
process_id: 2
v: 2
Using get_random_sleep_time_v2
order of processes is random but generated values are not consistent across runs:
run 1:
process_id: 3
v: 10
process_id: 1
v: 8
process_id: 2
v: 7
process_id: 0
v: 6
run 2:
process_id: 0
v: 8
process_id: 3
v: 10
process_id: 2
v: 10
process_id: 1
v: 8