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

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

8
void tas_spin_lock::lock() {
9
  backoff backoff_strategy;
10

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

19
bool tas_spin_lock::try_lock(unsigned int num_tries) {
20 21
  backoff backoff_strategy;

22
  while (true) {
23 24 25 26
    if (flag_.test_and_set(std::memory_order_acquire) == 0) {
      return true;
    }

27 28 29
    num_tries--;
    if (num_tries <= 0) {
      return false;
FritzFlorian committed
30
    }
31

32
    backoff_strategy.do_backoff();
33 34 35 36 37 38 39 40 41
  }
}

void tas_spin_lock::unlock() {
  flag_.clear(std::memory_order_release);
}

}
}
FritzFlorian committed
42
}