[flang] [llvm] [flang-rt] Runtime implementation of extended intrinsic function SECNDS() (PR #152021)
Peter Klausler via llvm-commits
llvm-commits at lists.llvm.org
Tue Aug 5 13:34:13 PDT 2025
klausler wrote:
> > I think that you can replace that loop with just a single compare & swap if zero. Only the first thread to ever execute it would succeed, and all later ones would fail and return the first thread's value.
>
> The other threads still need to wait for the initialization to happen, so I think the loop is unavoidable. (In early implementation, I didn't have a loop and threads came in quicker than the time value could be computed.) Also, I decided to put even `compare_exchange_strong()` inside the loop, because I read somewhere that even this function can still fail under some conditions (for example, see section in https://dev.to/pauljlucas/advanced-thread-safety-in-c-3ap5).
The atomic compare & swap if zero would be the initialization, I mean. The flow would be like:
```
auto UTCmidnight{atomicRead(atomicVar}};
if (UTCmidnight == 0) { // not initialized
// not initialized yet
UTCmidnight = computation;
CHECK(UTCmidnight > 0);
auto value{atomicCompareAndSwap(atomicVar, 0, UTCmidnight)}; // only stores a value once ever
if (oldValue != 0) {
// lost the race, my value wasn't stored
UTCmidnight = oldValue;
}
}
// all threads have the same UTCmidnight value from this point
https://github.com/llvm/llvm-project/pull/152021
More information about the llvm-commits
mailing list