From 27d6b0c7f517c17aa43a4305e49b3d34c74defc4 Mon Sep 17 00:00:00 2001 From: mutouyun Date: Sun, 20 Jan 2019 21:04:16 +0800 Subject: [PATCH] define spin_lock --- include/rw_lock.h | 21 ++++++++++++++++++--- src/memory/wrapper.hpp | 2 +- test/test_ipc.cpp | 1 + 3 files changed, 20 insertions(+), 4 deletions(-) diff --git a/include/rw_lock.h b/include/rw_lock.h index 945fa5d..19b9906 100644 --- a/include/rw_lock.h +++ b/include/rw_lock.h @@ -96,6 +96,21 @@ inline void sleep(K& k) noexcept { namespace ipc { +class spin_lock { + std::atomic lc_ { 0 }; + +public: + void lock(void) { + for (unsigned k = 0; + lc_.exchange(1, std::memory_order_acquire); + yield(k)) ; + } + + void unlock(void) { + lc_.store(0, std::memory_order_release); + } +}; + class rw_lock { using lc_ui_t = std::size_t; std::atomic lc_ { 0 }; @@ -121,9 +136,9 @@ public: yield(k); // other thread having w-lock } // wait for reading finished - for (unsigned k = 0; lc_.load(std::memory_order_acquire) & w_mask;) { - yield(k); - } + for (unsigned k = 0; + lc_.load(std::memory_order_acquire) & w_mask; + yield(k)) ; } void unlock() noexcept { diff --git a/src/memory/wrapper.hpp b/src/memory/wrapper.hpp index 44f6b10..64ea030 100644 --- a/src/memory/wrapper.hpp +++ b/src/memory/wrapper.hpp @@ -42,7 +42,7 @@ public: using alloc_policy = AllocP; private: - rw_lock lc_; + spin_lock lc_; std::multimap allocs_; struct alloc_t { diff --git a/test/test_ipc.cpp b/test/test_ipc.cpp index cd43438..b13b62f 100644 --- a/test/test_ipc.cpp +++ b/test/test_ipc.cpp @@ -305,6 +305,7 @@ void test_lock_performance() { << std::endl; benchmark_lc(); + benchmark_lc, W, R>(); benchmark_lc, W, R>(); benchmark_lc , W, R>(); benchmark_lc();