ttas_spin_lock.cpp 1.08 KB
Newer Older
FritzFlorian committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
#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;

                do {
                    while (flag_.load(std::memory_order_relaxed) == 1) {
                        tries++;
                        if (tries % yield_at_tries_ == 0) {
                            this_thread::yield();
                        }
                    }

                    expected = 0;
                } while (!flag_.compare_exchange_weak(expected, 1, std::memory_order_acquire));
            }

            bool ttas_spin_lock::try_lock() {
                int expected = 0;
                return flag_.load(std::memory_order_relaxed) == 0 && flag_.compare_exchange_weak(expected, 1, std::memory_order_acquire);
            }

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