ttas_spin_lock.cpp 1.03 KB
Newer Older
FritzFlorian committed
1 2 3 4
#include "pls/internal/helpers/profiler.h"
#include "pls/internal/base/ttas_spin_lock.h"

namespace pls {
5 6 7 8 9 10 11 12
namespace internal {
namespace base {

void ttas_spin_lock::lock() {
  PROFILE_LOCK("Acquire Lock")
  int tries = 0;
  int expected = 0;

13
  while (true) {
14 15 16 17 18
    while (flag_.load(std::memory_order_relaxed) == 1) {
      tries++;
      if (tries % yield_at_tries_ == 0) {
        this_thread::yield();
      }
FritzFlorian committed
19
    }
20 21

    expected = 0;
22 23 24 25
    if (flag_.compare_exchange_weak(expected, 1, std::memory_order_acquire)) {
      return;
    }
  }
26 27 28 29 30 31
}

bool ttas_spin_lock::try_lock(unsigned int num_tries) {
  PROFILE_LOCK("Try Acquire Lock")
  int expected = 0;

32
  while (true) {
33 34 35 36 37 38 39 40
    while (flag_.load(std::memory_order_relaxed) == 1) {
      num_tries--;
      if (num_tries <= 0) {
        return false;
      }
    }

    expected = 0;
41 42 43 44
    if (flag_.compare_exchange_weak(expected, 1, std::memory_order_acquire)) {
      return true;
    }
  }
45 46 47
}

void ttas_spin_lock::unlock() {
48
  PROFILE_LOCK("Unlock")
49 50 51 52 53
  flag_.store(0, std::memory_order_release);
}

}
}
FritzFlorian committed
54
}