Skip to content
This repository was archived by the owner on Feb 25, 2025. It is now read-only.

Replace 'std::mutex' inside 'SyncSwitch' to 'fml::SharedMutex' #32773

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions fml/synchronization/sync_switch.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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;
}

Expand Down
5 changes: 3 additions & 2 deletions fml/synchronization/sync_switch.h
Original file line number Diff line number Diff line change
Expand Up @@ -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 {

Expand Down Expand Up @@ -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);
Expand Down
29 changes: 29 additions & 0 deletions fml/synchronization/sync_switch_unittest.cc
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

#include "flutter/fml/synchronization/sync_switch.h"

#include <thread>

#include "gtest/gtest.h"

using fml::SyncSwitch;
Expand All @@ -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);
}