Random and fork
__peter__ at web.de
Wed Feb 6 17:47:38 CET 2013
Julien Le Goff wrote:
> Hi everyone,
> Today I came accross a behaviour I did not expect in python (I am using
> 2.7). In my program, random.random() always seemed to return the same
> number; it turned out to be related to the fact that I was using os.fork.
> See below a small program that illustrates this. It is easily fixed, but
> I'm interested in knowing why this happens. Can anybody give me a hint?
Those numbers are "pseudo"-random numbers -- the sequence of numbers
generated is fully determined by the state of the random number generator.
That state like anything else is copied by fork(). I you need "better"
randomness you can use random.SystemRandom:
> import random
> import os
random = random.SystemRandom()
> for i in xrange(10):
> pid = os.fork()
> if pid == 0:
> # uncommenting this fixes the problem
> # random.seed(os.getpid())
> print random.random()
More information about the Python-list