Skip to content

[libc] Make 'rand()' thread-safe using atomics instead of TLS #96692

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions libc/src/stdlib/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,7 @@ add_entrypoint_object(
DEPENDS
.rand_util
libc.include.stdlib
libc.src.__support.threads.sleep
)

add_entrypoint_object(
Expand Down
18 changes: 12 additions & 6 deletions libc/src/stdlib/rand.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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_strong(orig, x, cpp::MemoryOrder::ACQUIRE,
cpp::MemoryOrder::RELAXED))
return static_cast<int>((x * 0x2545F4914F6CDD1Dul) >> 32) & RAND_MAX;
sleep_briefly();
}
}

} // namespace LIBC_NAMESPACE
13 changes: 4 additions & 9 deletions libc/src/stdlib/rand_util.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,13 @@
//===----------------------------------------------------------------------===//

#include "src/stdlib/rand_util.h"
#include "src/__support/CPP/atomic.h"
#include "src/__support/macros/attributes.h"

namespace LIBC_NAMESPACE {

#ifdef LIBC_TARGET_ARCH_IS_GPU
// FIXME: Local GPU memory cannot be initialized so we cannot currently provide
// a standard compliant default value.
ThreadLocal<unsigned long> rand_next;
#else
// C standard 7.10p2: If 'rand' is called before 'srand' it is to proceed as if
// the 'srand' function was called with a value of '1'.
LIBC_THREAD_LOCAL unsigned long rand_next = 1;
#endif
// C standard 7.10p2: If 'rand' is called before 'srand' it is to
// proceed as if the 'srand' function was called with a value of '1'.
cpp::Atomic<unsigned long> rand_next = 1;

} // namespace LIBC_NAMESPACE
28 changes: 5 additions & 23 deletions libc/src/stdlib/rand_util.h
Original file line number Diff line number Diff line change
Expand Up @@ -9,33 +9,15 @@
#ifndef LLVM_LIBC_SRC_STDLIB_RAND_UTIL_H
#define LLVM_LIBC_SRC_STDLIB_RAND_UTIL_H

#include "src/__support/GPU/utils.h"
#include "src/__support/CPP/atomic.h"
#include "src/__support/macros/attributes.h"

namespace LIBC_NAMESPACE {

#ifdef LIBC_TARGET_ARCH_IS_GPU
// Implement thread local storage on the GPU using local memory. Each thread
// gets its slot in the local memory array and is private to the group.
// TODO: We need to implement the 'thread_local' keyword on the GPU. This is an
// inefficient and incomplete stand-in until that is done.
template <typename T> class ThreadLocal {
private:
static constexpr long MAX_THREADS = 1024;
[[clang::loader_uninitialized]] static inline gpu::Local<T>
storage[MAX_THREADS];

public:
LIBC_INLINE operator T() const { return storage[gpu::get_thread_id()]; }
LIBC_INLINE void operator=(const T &value) {
storage[gpu::get_thread_id()] = value;
}
};

extern ThreadLocal<unsigned long> rand_next;
#else
extern LIBC_THREAD_LOCAL unsigned long rand_next;
#endif
// The ISO C standard does not explicitly require thread-safe behavior for the
// generic `rand()` function. Some implementations expect it however, so we
// provide it here.
extern cpp::Atomic<unsigned long> rand_next;

} // namespace LIBC_NAMESPACE

Expand Down
4 changes: 3 additions & 1 deletion libc/src/stdlib/srand.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@

namespace LIBC_NAMESPACE {

LLVM_LIBC_FUNCTION(void, srand, (unsigned int seed)) { rand_next = seed; }
LLVM_LIBC_FUNCTION(void, srand, (unsigned int seed)) {
rand_next.store(seed, cpp::MemoryOrder::RELAXED);
}

} // namespace LIBC_NAMESPACE
3 changes: 0 additions & 3 deletions libc/test/src/stdlib/rand_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,12 @@ TEST(LlvmLibcRandTest, UnsetSeed) {
vals[i] = val;
}

// FIXME: The GPU implementation cannot initialize the seed correctly.
#ifndef LIBC_TARGET_ARCH_IS_GPU
// The C standard specifies that if 'srand' is never called it should behave
// as if 'srand' was called with a value of 1. If we seed the value with 1 we
// should get the same sequence as the unseeded version.
LIBC_NAMESPACE::srand(1);
for (size_t i = 0; i < 1000; ++i)
ASSERT_EQ(LIBC_NAMESPACE::rand(), vals[i]);
#endif
}

TEST(LlvmLibcRandTest, SetSeed) {
Expand Down
Loading