summaryrefslogtreecommitdiff
path: root/Lib/random.py
diff options
context:
space:
mode:
authorGuido van Rossum <guido@python.org>1998-05-29 17:51:31 +0000
committerGuido van Rossum <guido@python.org>1998-05-29 17:51:31 +0000
commit4f0db5d102e94d255b7638c5a8b73ca805db5226 (patch)
treed0671227294cf3a2f25c8bbfba9c50c1cc854294 /Lib/random.py
parent706e3ecf5d7a3ef221de68ff325db35935d16bea (diff)
downloadcpython-4f0db5d102e94d255b7638c5a8b73ca805db5226.tar.gz
Make gauss() semi-thread-safe. It can still give duplicate results,
but it can no longer raise an exception when called by several threads simultaneously.
Diffstat (limited to 'Lib/random.py')
-rw-r--r--Lib/random.py18
1 files changed, 14 insertions, 4 deletions
diff --git a/Lib/random.py b/Lib/random.py
index d95c324061..a19059cbe8 100644
--- a/Lib/random.py
+++ b/Lib/random.py
@@ -15,6 +15,10 @@
# Translated from anonymously contributed C/C++ source.
+# Multi-threading note: the random number generator used here is not
+# thread-safe; it is possible that two calls return the same random
+# value. See whrandom.py for more info.
+
import whrandom
from whrandom import random, uniform, randint, choice # Also for export!
from math import log, exp, pi, e, sqrt, acos, cos, sin
@@ -243,12 +247,18 @@ def gauss(mu, sigma):
# (Lambert Meertens)
# (corrected version; bug discovered by Mike Miller, fixed by LM)
+ # Multithreading note: When two threads call this function
+ # simultaneously, it is possible that they will receive the
+ # same return value. The window is very small though. To
+ # avoid this, you have to use a lock around all calls. (I
+ # didn't want to slow this down in the serial case by using a
+ # lock here.)
+
global gauss_next
- if gauss_next != None:
- z = gauss_next
- gauss_next = None
- else:
+ z = gauss_next
+ gauss_next = None
+ if z is None:
x2pi = random() * TWOPI
g2rad = sqrt(-2.0 * log(1.0 - random()))
z = cos(x2pi) * g2rad