[libc-commits] [libc] [libc] Make 'rand()' thread-safe using atomics instead of TLS (PR #96692)
Joseph Huber via libc-commits
libc-commits at lists.llvm.org
Tue Jun 25 18:04:56 PDT 2024
================
@@ -8,19 +8,25 @@
#include "src/stdlib/rand.h"
#include "src/__support/common.h"
+#include "src/__support/threads/sleep.h"
#include "src/stdlib/rand_util.h"
namespace LIBC_NAMESPACE {
// An implementation of the xorshift64star pseudo random number generator. This
// is a good general purpose generator for most non-cryptographics applications.
LLVM_LIBC_FUNCTION(int, rand, (void)) {
- unsigned long x = rand_next;
- x ^= x >> 12;
- x ^= x << 25;
- x ^= x >> 27;
- rand_next = x;
- return static_cast<int>((x * 0x2545F4914F6CDD1Dul) >> 32) & RAND_MAX;
+ unsigned long orig = rand_next.load(cpp::MemoryOrder::RELAXED);
+ for (;;) {
+ unsigned long x = orig;
----------------
jhuber6 wrote:
My understanding is that `atomic_compare_exchange` will write the new value back to `orig`, so it has the effect of an atomic read on failure.
https://github.com/llvm/llvm-project/pull/96692
More information about the libc-commits
mailing list