summaryrefslogtreecommitdiff
path: root/indra/llcommon/llrand.cpp
diff options
context:
space:
mode:
authorNat Goodspeed <nat@lindenlab.com>2023-11-17 14:31:21 -0500
committerNat Goodspeed <nat@lindenlab.com>2023-11-17 14:31:21 -0500
commit5fa7f69101a889009194eeddb927599d7536613f (patch)
treea742817431760d8fc947ad338743978605397f3a /indra/llcommon/llrand.cpp
parente7ae20c96fccdad06e39a3f8e5fe61a812029242 (diff)
SL-20546: Defend llrand's random generator against concurrent access
by making it thread_local.
Diffstat (limited to 'indra/llcommon/llrand.cpp')
-rw-r--r--indra/llcommon/llrand.cpp18
1 files changed, 5 insertions, 13 deletions
diff --git a/indra/llcommon/llrand.cpp b/indra/llcommon/llrand.cpp
index 8206bf8e0c..e4065e23bf 100644
--- a/indra/llcommon/llrand.cpp
+++ b/indra/llcommon/llrand.cpp
@@ -28,7 +28,6 @@
#include "llrand.h"
#include "lluuid.h"
-#include "mutex.h"
/**
* Through analysis, we have decided that we want to take values which
@@ -59,16 +58,9 @@
* to restore uniform distribution.
*/
-static std::mutex gRandomGeneratorMutex;
-static LLRandLagFib2281 gRandomGenerator(LLUUID::getRandomSeed());
-
-inline F64 ll_internal_random_unclamped()
-{
- // gRandomGenerator is a stateful static object, which is therefore not
- // inherently thread-safe. Lock it before use.
- std::unique_lock lk(gRandomGeneratorMutex);
- return gRandomGenerator();
-}
+// gRandomGenerator is a stateful static object, which is therefore not
+// inherently thread-safe.
+static thread_local LLRandLagFib2281 gRandomGenerator(LLUUID::getRandomSeed());
// no default implementation, only specific F64 and F32 specializations
template <typename REAL>
@@ -81,7 +73,7 @@ inline F64 ll_internal_random<F64>()
// CPUs (or at least multi-threaded processes) seem to
// occasionally give an obviously incorrect random number -- like
// 5^15 or something. Sooooo, clamp it as described above.
- F64 rv{ ll_internal_random_unclamped() };
+ F64 rv{ gRandomGenerator() };
if(!((rv >= 0.0) && (rv < 1.0))) return fmod(rv, 1.0);
return rv;
}
@@ -93,7 +85,7 @@ inline F32 ll_internal_random<F32>()
// Per Monty, it's important to clamp using the correct fmodf() rather
// than expanding to F64 for fmod() and then truncating back to F32. Prior
// to this change, we were getting sporadic ll_frand() == 1.0 results.
- F32 rv{ narrow(ll_internal_random_unclamped()) };
+ F32 rv{ narrow(gRandomGenerator()) };
if(!((rv >= 0.0f) && (rv < 1.0f))) return fmodf(rv, 1.0f);
return rv;
}