1 /* 2 * Copyright (c) 2025 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #ifndef COMMON_COMPONENTS_COMMON_SCOPED_LOCK_OBJECT_H 17 #define COMMON_COMPONENTS_COMMON_SCOPED_LOCK_OBJECT_H 18 19 #include "common_components/common/base_object.h" 20 #include "common_components/log/log.h" 21 namespace common { 22 class ScopedObjectLock { 23 public: ScopedObjectLock(BaseObject & obj)24 NO_INLINE_CC explicit ScopedObjectLock(BaseObject& obj) 25 { 26 do { 27 BaseStateWord::ForwardState state = obj.GetBaseStateWord().GetForwardState(); 28 if (state == BaseStateWord::ForwardState::FORWARDING || 29 state == BaseStateWord::ForwardState::FORWARDED || 30 state == BaseStateWord::ForwardState::NORMAL) { 31 lockedObj_ = &obj; 32 } else { 33 LOG_COMMON(FATAL) << "this state need to be dealt with when lock object, state: " << 34 static_cast<uint8_t>(state); 35 return; 36 } 37 BaseStateWord curState = lockedObj_->GetBaseStateWord(); 38 if (lockedObj_->TryLockExclusive(curState)) { 39 return; 40 } 41 } while (true); 42 } ~ScopedObjectLock()43 ~ScopedObjectLock() 44 { 45 LOGF_CHECK(lockedObj_ != nullptr) << "from copy is nullptr when unlock object\n"; 46 lockedObj_->UnlockExclusive(BaseStateWord::ForwardState::NORMAL); 47 } 48 49 private: 50 BaseObject* lockedObj_ = { nullptr }; 51 }; 52 } // namespace common 53 #endif // ~COMMON_COMPONENTS_COMMON_SCOPED_LOCK_OBJECT_H 54