Replace 'std::mutex' inside 'SyncSwitch' to 'fml::SharedMutex' (flutter/engine#32773)

This commit is contained in:
ColdPaleLight 2022-04-20 00:44:04 +08:00 committed by GitHub
parent f246a58daa
commit eb3479dd86
3 changed files with 37 additions and 5 deletions

View File

@ -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>(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;
}

View File

@ -7,9 +7,10 @@
#include <forward_list>
#include <functional>
#include <mutex>
#include <memory>
#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<fml::SharedMutex> mutex_;
bool value_;
FML_DISALLOW_COPY_AND_ASSIGN(SyncSwitch);

View File

@ -4,6 +4,8 @@
#include "flutter/fml/synchronization/sync_switch.h"
#include <thread>
#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);
}