[llvm-dev] Possibility of implementing a low-level naive lock purely with LLVM atomics?

Tim Northover via llvm-dev llvm-dev at lists.llvm.org
Tue Jul 24 01:43:03 PDT 2018


On Tue, 24 Jul 2018 at 08:37, mayuyu.io via llvm-dev
<llvm-dev at lists.llvm.org> wrote:
> What we basically is trying to achieve is to make sure that some BBs in the function are executed exactly once. Currently we use a GV to mark the execution status and at function start we load the value and do comparison, if executed we just directly branch bypass the BBs. To my best knowledge atomicrmw does the modify in place so we cant’t update the value only after the BB’s execution has finished

That probably has to involve more than just 2 states to work properly.
In C++ something like this:

enum {
  Uninitialized = 0,
  BeingInitialized = 1,
  Initialized = 2
};

std::atomic<int> Flag;

void foo() {
  if (Flag.load() != Initialized) {
    int CurrentStatus = Uninitialized;
    if (Flag.compare_exchange_strong(CurrentStatus, BeingInitialized)) {
      // We got the lock, do initialization here.
      [...]
      Flag.store(Initialized);
    } else {
      // Someone else beat us to it. Wait for the other thread to
finish initializing.
      while(Flag.load() != Initialized);
    }
  }
}

Cheers.

Tim.


More information about the llvm-dev mailing list