[libc-commits] [libc] [libc] Make 'rand()' thread-safe using atomics instead of TLS (PR #96692)
Roland McGrath via libc-commits
libc-commits at lists.llvm.org
Tue Jun 25 18:02:34 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;
+ x ^= x >> 12;
+ x ^= x << 25;
+ x ^= x >> 27;
+ if (rand_next.compare_exchange_weak(orig, x, cpp::MemoryOrder::ACQUIRE,
----------------
frobtech wrote:
I think this should use the strong version since it's only going to loop on failure.
https://github.com/llvm/llvm-project/pull/96692
More information about the libc-commits
mailing list