#include "pls/internal/helpers/profiler.h" #include "pls/internal/base/ttas_spin_lock.h" namespace pls { namespace internal { namespace base { void ttas_spin_lock::lock() { PROFILE_LOCK("Acquire Lock") int tries = 0; int expected = 0; while (true) { while (flag_.load(std::memory_order_relaxed) == 1) { tries++; if (tries % yield_at_tries_ == 0) { this_thread::yield(); } } expected = 0; if (flag_.compare_exchange_weak(expected, 1, std::memory_order_acquire)) { return; } } } bool ttas_spin_lock::try_lock(unsigned int num_tries) { PROFILE_LOCK("Try Acquire Lock") int expected = 0; while (true) { while (flag_.load(std::memory_order_relaxed) == 1) { num_tries--; if (num_tries <= 0) { return false; } } expected = 0; if (flag_.compare_exchange_weak(expected, 1, std::memory_order_acquire)) { return true; } } } void ttas_spin_lock::unlock() { PROFILE_LOCK("Unlock") flag_.store(0, std::memory_order_release); } } } }