Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit d03e119

Browse files
committed
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.
1 parent b39e461 commit d03e119

1 file changed

Lines changed: 14 additions & 4 deletions

File tree

Lib/random.py

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,10 @@
1515

1616
# Translated from anonymously contributed C/C++ source.
1717

18+
# Multi-threading note: the random number generator used here is not
19+
# thread-safe; it is possible that two calls return the same random
20+
# value. See whrandom.py for more info.
21+
1822
import whrandom
1923
from whrandom import random, uniform, randint, choice # Also for export!
2024
from math import log, exp, pi, e, sqrt, acos, cos, sin
@@ -243,12 +247,18 @@ def gauss(mu, sigma):
243247
# (Lambert Meertens)
244248
# (corrected version; bug discovered by Mike Miller, fixed by LM)
245249

250+
# Multithreading note: When two threads call this function
251+
# simultaneously, it is possible that they will receive the
252+
# same return value. The window is very small though. To
253+
# avoid this, you have to use a lock around all calls. (I
254+
# didn't want to slow this down in the serial case by using a
255+
# lock here.)
256+
246257
global gauss_next
247258

248-
if gauss_next != None:
249-
z = gauss_next
250-
gauss_next = None
251-
else:
259+
z = gauss_next
260+
gauss_next = None
261+
if z is None:
252262
x2pi = random() * TWOPI
253263
g2rad = sqrt(-2.0 * log(1.0 - random()))
254264
z = cos(x2pi) * g2rad

0 commit comments

Comments
 (0)