From b80a710fb038b9a701952ea27fcfd48de701e9f2 Mon Sep 17 00:00:00 2001 From: hai007 Date: Wed, 19 Apr 2023 13:48:51 -0700 Subject: [PATCH] Fix data race problem caused by a simulated_clock PiperOrigin-RevId: 525540869 --- internal/platform/medium_environment.cc | 7 ++++++- internal/platform/medium_environment.h | 2 +- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/internal/platform/medium_environment.cc b/internal/platform/medium_environment.cc index 600ce8fd..ead9fcc6 100644 --- a/internal/platform/medium_environment.cc +++ b/internal/platform/medium_environment.cc @@ -50,6 +50,7 @@ void MediumEnvironment::Start(EnvironmentConfig config) { NEARBY_LOGS(INFO) << "MediumEnvironment::Start()"; config_ = std::move(config); if (config_.use_simulated_clock) { + MutexLock lock(&mutex_); simulated_clock_ = std::make_unique(); } Reset(); @@ -60,8 +61,11 @@ void MediumEnvironment::Stop() { if (enabled_.exchange(false)) { NEARBY_LOGS(INFO) << "MediumEnvironment::Stop()"; Sync(false); + if (config_.use_simulated_clock) { + MutexLock lock(&mutex_); + simulated_clock_.reset(); + } config_ = {}; - simulated_clock_.reset(); } } @@ -1205,6 +1209,7 @@ void MediumEnvironment::SetFeatureFlags(const FeatureFlags::Flags& flags) { } absl::optional MediumEnvironment::GetSimulatedClock() { + MutexLock lock(&mutex_); if (simulated_clock_) { return absl::optional(simulated_clock_.get()); } diff --git a/internal/platform/medium_environment.h b/internal/platform/medium_environment.h index 4bbd2d86..b0865e33 100644 --- a/internal/platform/medium_environment.h +++ b/internal/platform/medium_environment.h @@ -511,7 +511,7 @@ class MediumEnvironment { bool use_valid_peer_connection_ = true; absl::Duration peer_connection_latency_ = absl::ZeroDuration(); - std::unique_ptr simulated_clock_; + std::unique_ptr simulated_clock_ ABSL_GUARDED_BY(mutex_); }; } // namespace nearby