tas_spin_lock.cpp 856 Bytes
Newer Older
FritzFlorian committed
1 2
#include "pls/internal/helpers/profiler.h"
#include "pls/internal/base/tas_spin_lock.h"
3
#include "pls/internal/base/backoff.h"
FritzFlorian committed
4 5

namespace pls {
6 7
namespace internal {
namespace base {
FritzFlorian committed
8

9 10
void tas_spin_lock::lock() {
  PROFILE_LOCK("Acquire Lock")
11
  backoff backoff_strategy;
12

13
  while (true) {
14 15 16
    if (flag_.test_and_set(std::memory_order_acquire) == 0) {
      return;
    }
17
    backoff_strategy.do_backoff();
18 19
  }
}
FritzFlorian committed
20

21 22
bool tas_spin_lock::try_lock(unsigned int num_tries) {
  PROFILE_LOCK("Try Acquire Lock")
23 24
  backoff backoff_strategy;

25
  while (true) {
26 27 28 29
    if (flag_.test_and_set(std::memory_order_acquire) == 0) {
      return true;
    }

30 31 32
    num_tries--;
    if (num_tries <= 0) {
      return false;
FritzFlorian committed
33
    }
34

35
    backoff_strategy.do_backoff();
36 37 38 39
  }
}

void tas_spin_lock::unlock() {
40
  PROFILE_LOCK("Unlock")
41 42 43 44 45
  flag_.clear(std::memory_order_release);
}

}
}
FritzFlorian committed
46
}