[flang-commits] [PATCH] D127023: [flang][runtime] Don't let random seed queries change the sequence
Peter Klausler via Phabricator via flang-commits
flang-commits at lists.llvm.org
Fri Jun 3 15:59:19 PDT 2022
klausler created this revision.
klausler added a reviewer: vdonaldson.
klausler added a project: Flang.
Herald added a subscriber: jdoerfert.
Herald added a project: All.
klausler requested review of this revision.
When the current seed of the pseudo-random generator is queried
with CALL RANDOM_SEED(GET=n), that query should not change the
stream of pseudo-random numbers produced by CALL RANDOM_NUMBER().
https://reviews.llvm.org/D127023
Files:
flang/runtime/random.cpp
Index: flang/runtime/random.cpp
===================================================================
--- flang/runtime/random.cpp
+++ flang/runtime/random.cpp
@@ -40,6 +40,19 @@
static Lock lock;
static Generator generator;
+static std::optional<GeneratedWord> nextValue;
+
+// Call only with lock held
+static GeneratedWord GetNextValue() {
+ GeneratedWord result;
+ if (nextValue.has_value()) {
+ result = *nextValue;
+ nextValue.reset();
+ } else {
+ result = generator();
+ }
+ return result;
+}
template <typename REAL, int PREC>
inline void Generate(const Descriptor &harvest) {
@@ -54,12 +67,21 @@
{
CriticalSection critical{lock};
for (std::size_t j{0}; j < elements; ++j) {
- Int fraction{generator()};
- if constexpr (words > 1) {
- for (std::size_t k{1}; k < words; ++k) {
- static constexpr auto rangeMask{(GeneratedWord{1} << rangeBits) - 1};
- GeneratedWord word{(generator() - generator.min()) & rangeMask};
- fraction = (fraction << rangeBits) | word;
+ while (true) {
+ Int fraction{GetNextValue()};
+ if constexpr (words > 1) {
+ for (std::size_t k{1}; k < words; ++k) {
+ static constexpr auto rangeMask{
+ (GeneratedWord{1} << rangeBits) - 1};
+ GeneratedWord word{(GetNextValue() - generator.min()) & rangeMask};
+ fraction = (fraction << rangeBits) | word;
+ }
+ }
+ fraction >>= words * rangeBits - PREC;
+ REAL next{std::ldexp(static_cast<REAL>(fraction), -(PREC + 1))};
+ if (next >= 0.0 && next < 1.0) {
+ *harvest.Element<REAL>(at) = next;
+ break;
}
}
fraction >>= words * rangeBits - PREC;
@@ -155,6 +177,7 @@
{
CriticalSection critical{lock};
generator.seed(seed);
+ nextValue = seed;
}
}
@@ -177,8 +200,8 @@
GeneratedWord seed;
{
CriticalSection critical{lock};
- seed = generator();
- generator.seed(seed);
+ seed = GetNextValue();
+ nextValue = seed;
}
switch (kind) {
case 4:
-------------- next part --------------
A non-text attachment was scrubbed...
Name: D127023.434181.patch
Type: text/x-patch
Size: 2096 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/flang-commits/attachments/20220603/a652c63a/attachment.bin>
More information about the flang-commits
mailing list