New submission from STINNER Victor:

When reviewing the issue #30030, it reminded me that the random module "doesn't 
support fork": after fork, the parent and the child produce the same "random" 
number sequence.

I suggest to add a quick note about that: not a warning, just a note, as a 
reminder.

There is an exception: SystemRandom produces a different sequence after fork, 
since it uses os.urandom() (which runs in the kernel).

I am tempted to propose a solution in the note like using SystemRandom, but I'm 
not sure that it's a good idea. Some users may misunderstood the note and 
always use SystemRandom where random.Random is just fine for their needs.

Proposed note:

The random module doesn't support fork: the parent and the child process will 
produce the same number sequence.

Proposed solution:

If your code uses os.fork(), a workaround is to check if os.getpid() changes 
and in that case, create a new Random instance or reseed the RNG in the child 
process.

--

The tempfile module reminds the pid and instanciates a new RNG on fork.

Another option is to not add a note, but implement the workaround directly into 
the random module. But I don't think that it's worth it. Forking is a rare 
usecase, and calling os.getpid() may slowdown the random module. (I don't 
recall if os.getpid() requires a syscall or not, I'm quite sure that it's 
optimized at least on Linux to avoid a real syscall.)

----------
messages: 291534
nosy: haypo
priority: normal
severity: normal
status: open
title: Document that the random module doesn't support fork
versions: Python 3.7

_______________________________________
Python tracker <rep...@bugs.python.org>
<http://bugs.python.org/issue30051>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to