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

namespace pls {
5 6 7 8 9
namespace internal {
namespace base {

void ttas_spin_lock::lock() {
  int expected = 0;
10
  backoff backoff_;
11

12
  while (true) {
13 14
    while (flag_.load(std::memory_order_relaxed) == 1)
      system_details::relax_cpu(); // Spin
15 16

    expected = 0;
17 18 19
    if (flag_.compare_exchange_weak(expected, 1, std::memory_order_acquire)) {
      return;
    }
20
    backoff_.do_backoff();
21
  }
22 23 24 25
}

bool ttas_spin_lock::try_lock(unsigned int num_tries) {
  int expected = 0;
26
  backoff backoff_;
27

28
  while (true) {
29
    while (flag_.load() == 1) {
30 31 32 33
      num_tries--;
      if (num_tries <= 0) {
        return false;
      }
34
      system_details::relax_cpu();
35 36 37
    }

    expected = 0;
38 39 40
    if (flag_.compare_exchange_weak(expected, 1, std::memory_order_acquire)) {
      return true;
    }
41 42 43 44 45
    num_tries--;
    if (num_tries <= 0) {
      return false;
    }
    backoff_.do_backoff();
46
  }
47 48 49 50 51 52 53 54
}

void ttas_spin_lock::unlock() {
  flag_.store(0, std::memory_order_release);
}

}
}
FritzFlorian committed
55
}