spin_lock.cpp 916 Bytes
Newer Older
1 2 3 4 5
#include "pls/internal/base/spin_lock.h"

namespace pls {
    namespace internal {
        namespace base {
6 7 8
            // TODO: Research/Measure how the memory fences/orders influence this.
            //       For now we simply try to be safe by forcing this lock to
            //       also act as a strict memory fence.
9 10 11 12 13 14 15 16
            void spin_lock::lock() {
                int tries = 0;
                while (flag_.test_and_set(std::memory_order_acquire)) {
                    tries++;
                    if (tries % yield_at_tries_ == 0) {
                        this_thread::yield();
                    }
                }
17
                std::atomic_thread_fence(std::memory_order_seq_cst);
18 19 20 21
            }

            void spin_lock::unlock() {
                flag_.clear(std::memory_order_release);
22
                std::atomic_thread_fence(std::memory_order_seq_cst);
23
            }
24 25 26
        }
    }
}