random number generator thread safety

Mike Brown mike at skew.org
Tue Nov 8 16:05:23 EST 2005


I have questions about thread safety in the 'random' module.

When using the random.Random class (be it Mersenne Twister or Wichmann-Hill 
based), is it sufficiently thread-safe (preserving entropy and guarding 
against attack) to just have each thread work with its own random.Random 
instance? Or do I need to wrap my calls to each instance's methods to use 
locks? Wichmann-Hill in particular has the warning in its .random() 
vulnerability; do I need to make an exception for that case?

What about when using the random.SystemRandom class (be it based on 
/dev/urandom or CryptGenRandom based)? Should I be doing anything in my code 
to ensure that /dev/urandom, for example, is polled serially? (I thought I 
read somewhere that this was advisable). SystemRandom claims it has no state, 
which may be true at the Python class level, but is that guaranteed to be true 
for the underlying RNG?

Also, side note: The doc string for random.SystemRandom says "Not available on 
all systems (see os.urandom() for details)" ...but os.urandom()'s doc string 
provides no details. Actually, os.urandom() and random.SystemRandom are 
"available" on all systems (they exist and can be called/instantiated), but 
os.urandom() can raise a NotImplementedError (any time it is called, in 
theory), therefore random.SystemRandom's methods can fail with a bubbled-up 
NotImplementedError (on non-win32 OSes, at least). At the very least, this 
should be documented. I'm not in a position to submit a patch, but will submit 
a documentation bug report if so advised.

Thanks,
Mike



More information about the Python-list mailing list