From 2607f10944b08ee672891f0ed613c5ae8cd460f5 Mon Sep 17 00:00:00 2001 From: ColdPaleLight Date: Tue, 19 Apr 2022 20:52:09 +0800 Subject: [PATCH] Replace 'std::mutex' inside 'SyncSwitch' to 'fml::SharedMutex' --- fml/synchronization/sync_switch.cc | 8 +++--- fml/synchronization/sync_switch.h | 5 ++-- fml/synchronization/sync_switch_unittest.cc | 29 +++++++++++++++++++++ 3 files changed, 37 insertions(+), 5 deletions(-) diff --git a/fml/synchronization/sync_switch.cc b/fml/synchronization/sync_switch.cc index 5721703141670..9add886975577 100644 --- a/fml/synchronization/sync_switch.cc +++ b/fml/synchronization/sync_switch.cc @@ -18,10 +18,12 @@ SyncSwitch::Handlers& SyncSwitch::Handlers::SetIfFalse( return *this; } -SyncSwitch::SyncSwitch(bool value) : value_(value) {} +SyncSwitch::SyncSwitch(bool value) + : mutex_(std::unique_ptr(fml::SharedMutex::Create())), + value_(value) {} void SyncSwitch::Execute(const SyncSwitch::Handlers& handlers) const { - std::scoped_lock guard(mutex_); + fml::SharedLock lock(*mutex_); if (value_) { handlers.true_handler(); } else { @@ -30,7 +32,7 @@ void SyncSwitch::Execute(const SyncSwitch::Handlers& handlers) const { } void SyncSwitch::SetSwitch(bool value) { - std::scoped_lock guard(mutex_); + fml::UniqueLock lock(*mutex_); value_ = value; } diff --git a/fml/synchronization/sync_switch.h b/fml/synchronization/sync_switch.h index 08451c7476f89..470072fe4f25d 100644 --- a/fml/synchronization/sync_switch.h +++ b/fml/synchronization/sync_switch.h @@ -7,9 +7,10 @@ #include #include -#include +#include #include "flutter/fml/macros.h" +#include "flutter/fml/synchronization/shared_mutex.h" namespace fml { @@ -53,7 +54,7 @@ class SyncSwitch { void SetSwitch(bool value); private: - mutable std::mutex mutex_; + mutable std::unique_ptr mutex_; bool value_; FML_DISALLOW_COPY_AND_ASSIGN(SyncSwitch); diff --git a/fml/synchronization/sync_switch_unittest.cc b/fml/synchronization/sync_switch_unittest.cc index 09994496cf907..3f1365c87e2ba 100644 --- a/fml/synchronization/sync_switch_unittest.cc +++ b/fml/synchronization/sync_switch_unittest.cc @@ -4,6 +4,8 @@ #include "flutter/fml/synchronization/sync_switch.h" +#include + #include "gtest/gtest.h" using fml::SyncSwitch; @@ -28,3 +30,30 @@ TEST(SyncSwitchTest, NoopIfUndefined) { syncSwitch.Execute(SyncSwitch::Handlers()); EXPECT_FALSE(switchValue); } + +TEST(SyncSwitchTest, SharedLock) { + SyncSwitch syncSwitch; + syncSwitch.SetSwitch(true); + bool switchValue1 = false; + bool switchValue2 = false; + + std::thread thread1([&] { + syncSwitch.Execute( + SyncSwitch::Handlers() + .SetIfTrue([&] { + switchValue1 = true; + + std::thread thread2([&]() { + syncSwitch.Execute( + SyncSwitch::Handlers() + .SetIfTrue([&] { switchValue2 = true; }) + .SetIfFalse([&] { switchValue2 = false; })); + }); + thread2.join(); + }) + .SetIfFalse([&] { switchValue1 = false; })); + }); + thread1.join(); + EXPECT_TRUE(switchValue1); + EXPECT_TRUE(switchValue2); +}