diff --git a/frameworks/native/include/sensor_agent_proxy.h b/frameworks/native/include/sensor_agent_proxy.h index b5258f7da594da4b4559e2c6aa942647383d1033..5d58e1126257e9a5c137c0f866cee8838b2f5620 100644 --- a/frameworks/native/include/sensor_agent_proxy.h +++ b/frameworks/native/include/sensor_agent_proxy.h @@ -58,6 +58,7 @@ private: int32_t ConvertSensorInfos() const; void ClearSensorInfos() const; std::set GetSubscribeUserCallback(int32_t sensorId); + bool IsSubscribeMapEmpty() const; static std::recursive_mutex subscribeMutex_; static std::mutex chanelMutex_; OHOS::sptr dataChannel_ = nullptr; diff --git a/frameworks/native/src/sensor_agent_proxy.cpp b/frameworks/native/src/sensor_agent_proxy.cpp index 53b1715ea2632ac5a6b72f362f0080e0f5f30daf..0d0fd18a81cfd9ad92f799cd2c4d956170f4805f 100644 --- a/frameworks/native/src/sensor_agent_proxy.cpp +++ b/frameworks/native/src/sensor_agent_proxy.cpp @@ -265,6 +265,12 @@ int32_t SensorAgentProxy::SubscribeSensor(int32_t sensorId, const SensorUser *us return OHOS::Sensors::SUCCESS; } +bool SensorAgentProxy::IsSubscribeMapEmpty() const +{ + std::lock_guard subscribeLock(subscribeMutex_); + return subscribeMap_.empty(); +} + int32_t SensorAgentProxy::UnsubscribeSensor(int32_t sensorId, const SensorUser *user) { SEN_HILOGI("In, sensorId:%{public}d", sensorId); @@ -274,27 +280,29 @@ int32_t SensorAgentProxy::UnsubscribeSensor(int32_t sensorId, const SensorUser * SEN_HILOGE("sensorId is invalid, %{public}d", sensorId); return PARAMETER_ERROR; } - std::lock_guard subscribeLock(subscribeMutex_); - if (unsubscribeMap_.find(sensorId) == unsubscribeMap_.end()) { - SEN_HILOGE("Deactivate sensorId first"); - return OHOS::Sensors::ERROR; - } - auto& unsubscribeSet = unsubscribeMap_[sensorId]; - if (unsubscribeSet.find(user) == unsubscribeSet.end()) { - SEN_HILOGE("Deactivate user first"); - return OHOS::Sensors::ERROR; + { + std::lock_guard subscribeLock(subscribeMutex_); + if (unsubscribeMap_.find(sensorId) == unsubscribeMap_.end()) { + SEN_HILOGE("Deactivate sensorId first"); + return OHOS::Sensors::ERROR; + } + auto& unsubscribeSet = unsubscribeMap_[sensorId]; + if (unsubscribeSet.find(user) == unsubscribeSet.end()) { + SEN_HILOGE("Deactivate user first"); + return OHOS::Sensors::ERROR; + } + unsubscribeSet.erase(user); + if (unsubscribeSet.empty()) { + unsubscribeMap_.erase(sensorId); + } } - if (subscribeMap_.empty()) { + if (IsSubscribeMapEmpty()) { int32_t ret = DestroySensorDataChannel(); if (ret != ERR_OK) { SEN_HILOGE("Destroy data channel fail, ret:%{public}d", ret); return ret; } } - unsubscribeSet.erase(user); - if (unsubscribeSet.empty()) { - unsubscribeMap_.erase(sensorId); - } if (PrintSensorData::GetInstance().IsContinuousType(sensorId)) { PrintSensorData::GetInstance().RemovePrintUserInfo(user->callback); }