I'm working with ruby 2.4.1 + parallel 1.11.2. I'm running the following in irb:
require 'parallel'
srand(1)
Parallel.map([0, 1], in_processes: 2) { |i| puts "in process #{i}; rand => #{rand}" }
My understanding is that when in_processes is specified, Parallel.map forks the process and then executes the loop body. Given that, I expect both processes to have the same global state and therefore I had expected that both would output the same random number. However, here's what I get:
irb(main):003:0> Parallel.map([0, 1], in_processes: 2) { |i| puts "in process #{i}; rand => #{rand}" }
in process 1; rand => 0.48721687007281356
in process 0; rand => 0.7502824863668285
=> [nil, nil]
For the record, if I execute srand(1) and then rand, I get 0.417022004702574, so it appears that neither process got the random number seed which I set. I can get the behavior I want by setting the random number seed within the loop, but before I do that I'm trying to understand why it doesn't work to put the seed outside the loop.
I'm trying to make sense of this situation. Is this behavior somehow specific to the random number generator, so I wouldn't necessarily have the same problem (namely, expected shared initial state and didn't get it) with other objects? Or is Parallel not really having the same effect as a plain fork system call?
The documentation about Parallel with in_processes led me to believe that it acted like fork, but that doesn't seem to be the case here, hence my surprise.
Aucun commentaire:
Enregistrer un commentaire