From ca7ae0d53904e1aef578406dc776e8ff74e93f4b Mon Sep 17 00:00:00 2001 From: Ilya Matveev Date: Thu, 30 Sep 2021 18:07:02 +0700 Subject: [PATCH] [K/N][Runtime] Use std::atomic_flag in SpinLock --- kotlin-native/runtime/src/main/cpp/Mutex.hpp | 22 +++++++------------- 1 file changed, 8 insertions(+), 14 deletions(-) diff --git a/kotlin-native/runtime/src/main/cpp/Mutex.hpp b/kotlin-native/runtime/src/main/cpp/Mutex.hpp index bcd3b3f7ff6..f75352d51b2 100644 --- a/kotlin-native/runtime/src/main/cpp/Mutex.hpp +++ b/kotlin-native/runtime/src/main/cpp/Mutex.hpp @@ -17,7 +17,7 @@ #ifndef RUNTIME_MUTEX_H #define RUNTIME_MUTEX_H -#include +#include #include #include "KAssert.h" @@ -37,20 +37,17 @@ template <> class SpinLock : private Pinned { public: void lock() noexcept { - while (!__sync_bool_compare_and_swap(&atomicInt, 0, 1)) { + while(flag_.test_and_set(std::memory_order_acquire)) { std::this_thread::yield(); } } void unlock() noexcept { - if (!__sync_bool_compare_and_swap(&atomicInt, 1, 0)) { - RuntimeAssert(false, "Unable to unlock"); - } + flag_.clear(std::memory_order_release); } private: - // TODO: Consider using `std::atomic_flag`. - int32_t atomicInt = 0; + std::atomic_flag flag_ = ATOMIC_FLAG_INIT; }; template <> @@ -58,25 +55,22 @@ class SpinLock : private Pinned { public: void lock() noexcept { // Fast path without thread state switching. - if (__sync_bool_compare_and_swap(&atomicInt, 0, 1)) { + if (!flag_.test_and_set(std::memory_order_acquire)) { return; } kotlin::NativeOrUnregisteredThreadGuard guard(/* reentrant = */ true); - while (!__sync_bool_compare_and_swap(&atomicInt, 0, 1)) { + while (flag_.test_and_set(std::memory_order_acquire)) { std::this_thread::yield(); } } void unlock() noexcept { - if (!__sync_bool_compare_and_swap(&atomicInt, 1, 0)) { - RuntimeAssert(false, "Unable to unlock"); - } + flag_.clear(std::memory_order_release); } private: - // TODO: Consider using `std::atomic_flag`. - int32_t atomicInt = 0; + std::atomic_flag flag_ = ATOMIC_FLAG_INIT; }; } // namespace kotlin