1 /* 2 * Copyright (c) 2024 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 ECMASCRIPT_MUTATOR_LOCK_H 17 #define ECMASCRIPT_MUTATOR_LOCK_H 18 19 #include "ecmascript/platform/mutex.h" 20 21 namespace panda::ecmascript { 22 23 class MutatorLock : public RWLock { 24 #ifndef NDEBUG 25 public: 26 enum MutatorLockState { UNLOCKED, RDLOCK, WRLOCK }; 27 void ReadLock(); 28 void WriteLock(); 29 bool TryReadLock(); 30 bool TryWriteLock(); 31 void Unlock(); 32 bool HasLock() const; 33 34 private: 35 MutatorLockState GetState() const; 36 void SetState(MutatorLockState newState); 37 #endif 38 }; 39 40 class SuspendBarrier { 41 public: SuspendBarrier()42 SuspendBarrier() : passBarrierCount_(0) 43 { 44 } 45 SuspendBarrier(int32_t count)46 explicit SuspendBarrier(int32_t count) : passBarrierCount_(count) 47 { 48 } 49 50 void Wait(); 51 Pass()52 void Pass() 53 { 54 PassCount(-1); 55 } 56 PassStrongly()57 void PassStrongly() 58 { 59 passBarrierCount_.fetch_sub(1, std::memory_order_seq_cst); 60 } 61 Initialize(int32_t count)62 void Initialize(int32_t count) 63 { 64 passBarrierCount_.store(count, std::memory_order_relaxed); 65 } 66 Increment(int32_t delta)67 void Increment(int32_t delta) 68 { 69 PassCount(delta); 70 Wait(); 71 } 72 73 private: 74 void PassCount(int32_t delta); 75 std::atomic<int32_t> passBarrierCount_; 76 }; 77 78 } // namespace panda::ecmascript 79 #endif // ECMASCRIPT_MUTATOR_LOCK_H