[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:33 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;
----------------
frobtech wrote:

This should do the load at the top of the loop, not outside the loop.
If the CAS fails, you need to start over from the new "current" state.


https://github.com/llvm/llvm-project/pull/96692


More information about the libc-commits mailing list