define spin_lock

This commit is contained in:
mutouyun 2019-01-20 21:04:16 +08:00
parent a7d9a3d476
commit 27d6b0c7f5
3 changed files with 20 additions and 4 deletions

View File

@ -96,6 +96,21 @@ inline void sleep(K& k) noexcept {
namespace ipc {
class spin_lock {
std::atomic<std::size_t> 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_ui_t> 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 {

View File

@ -42,7 +42,7 @@ public:
using alloc_policy = AllocP;
private:
rw_lock lc_;
spin_lock lc_;
std::multimap<std::size_t, alloc_policy*> allocs_;
struct alloc_t {

View File

@ -305,6 +305,7 @@ void test_lock_performance() {
<< std::endl;
benchmark_lc<ipc::rw_lock , W, R>();
benchmark_lc<lc_wrapper< ipc::spin_lock>, W, R>();
benchmark_lc<lc_wrapper<capo::spin_lock>, W, R>();
benchmark_lc<lc_wrapper<std::mutex> , W, R>();
benchmark_lc<std::shared_timed_mutex , W, R>();