spin_lock.cpp 778 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
            void spin_lock::lock() {
                int tries = 0;
11
                while (flag_.test_and_set(std::memory_order_seq_cst)) {
12 13 14 15 16 17 18 19
                    tries++;
                    if (tries % yield_at_tries_ == 0) {
                        this_thread::yield();
                    }
                }
            }

            void spin_lock::unlock() {
20
                flag_.clear(std::memory_order_seq_cst);
21
            }
22 23 24
        }
    }
}