mirror of
https://github.com/python/cpython.git
synced 2025-10-17 12:18:23 +00:00
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.
This commit is contained in:
parent
b39e461b89
commit
d03e1197cb
1 changed files with 14 additions and 4 deletions
|
@ -15,6 +15,10 @@
|
||||||
|
|
||||||
# Translated from anonymously contributed C/C++ source.
|
# 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
|
import whrandom
|
||||||
from whrandom import random, uniform, randint, choice # Also for export!
|
from whrandom import random, uniform, randint, choice # Also for export!
|
||||||
from math import log, exp, pi, e, sqrt, acos, cos, sin
|
from math import log, exp, pi, e, sqrt, acos, cos, sin
|
||||||
|
@ -243,12 +247,18 @@ def gauss(mu, sigma):
|
||||||
# (Lambert Meertens)
|
# (Lambert Meertens)
|
||||||
# (corrected version; bug discovered by Mike Miller, fixed by LM)
|
# (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
|
global gauss_next
|
||||||
|
|
||||||
if gauss_next != None:
|
z = gauss_next
|
||||||
z = gauss_next
|
gauss_next = None
|
||||||
gauss_next = None
|
if z is None:
|
||||||
else:
|
|
||||||
x2pi = random() * TWOPI
|
x2pi = random() * TWOPI
|
||||||
g2rad = sqrt(-2.0 * log(1.0 - random()))
|
g2rad = sqrt(-2.0 * log(1.0 - random()))
|
||||||
z = cos(x2pi) * g2rad
|
z = cos(x2pi) * g2rad
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue