From a04d4d01eb8e38b8ec5367114b5581bd64eee17e Mon Sep 17 00:00:00 2001 From: lichao <lichao@aiotlink.com> Date: 星期五, 23 四月 2021 15:44:12 +0800 Subject: [PATCH] mutex unlock check timeout to avoid double unlock. --- src/shm.h | 2 +- utest/api_test.cpp | 13 +++++++++++-- src/shm.cpp | 10 ++++++++++ 3 files changed, 22 insertions(+), 3 deletions(-) diff --git a/src/shm.cpp b/src/shm.cpp index d499b16..6d7dccd 100644 --- a/src/shm.cpp +++ b/src/shm.cpp @@ -46,6 +46,16 @@ std::this_thread::yield(); } } +void MutexWithTimeLimit::unlock() +{ + auto old_time = last_lock_time_.load(); + if (Now() - old_time > limit_) { + } else { + if (last_lock_time_.compare_exchange_strong(old_time, Now())) { + mutex_.unlock(); + } + } +} SharedMemory::SharedMemory(const std::string &name, const uint64_t size) : mshm_t(open_or_create, name.c_str(), size, 0, AllowAll()), diff --git a/src/shm.h b/src/shm.h index 5bf8e41..0e834c3 100644 --- a/src/shm.h +++ b/src/shm.h @@ -76,7 +76,7 @@ ~MutexWithTimeLimit() { static_assert(std::is_pod<Duration>::value); } bool try_lock(); void lock(); - void unlock() { mutex_.unlock(); } + void unlock(); }; // typedef boost::interprocess::interprocess_mutex Mutex; diff --git a/utest/api_test.cpp b/utest/api_test.cpp index 200ae99..79236ba 100644 --- a/utest/api_test.cpp +++ b/utest/api_test.cpp @@ -151,7 +151,16 @@ } st_.nlock_ += n; } - void unlock() { mutex_.unlock(); } + void unlock() + { + auto old_time = last_lock_time_.load(); + if (Now() - old_time > limit_) { + } else { + if (last_lock_time_.compare_exchange_strong(old_time, Now())) { + mutex_.unlock(); + } + } + } }; namespace @@ -210,7 +219,7 @@ TLMutex mutex; // CasMutex mutex; auto Lock = [&]() { - for (int i = 0; i < 1000 * 100; ++i) { + for (int i = 0; i < 1000 * 1000 * 10; ++i) { mutex.lock(); mutex.unlock(); } -- Gitblit v1.8.0