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

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

8 9 10
void tas_spin_lock::lock() {
  PROFILE_LOCK("Acquire Lock")
  int tries = 0;
11
  while (true) {
12 13 14 15
    tries++;
    if (tries % yield_at_tries_ == 0) {
      this_thread::yield();
    }
16 17 18 19

    if (flag_.test_and_set(std::memory_order_acquire) == 0) {
      return;
    }
20 21
  }
}
FritzFlorian committed
22

23 24
bool tas_spin_lock::try_lock(unsigned int num_tries) {
  PROFILE_LOCK("Try Acquire Lock")
25
  while (true) {
26 27 28
    num_tries--;
    if (num_tries <= 0) {
      return false;
FritzFlorian committed
29
    }
30 31 32 33

    if (flag_.test_and_set(std::memory_order_acquire) == 0) {
      return true;
    }
34 35 36 37
  }
}

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

}
}
FritzFlorian committed
44
}