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_INTERFACES_THREAD_THREAD_STATE_H 17 #define COMMON_INTERFACES_THREAD_THREAD_STATE_H 18 19 #include <atomic> 20 #include <cstdint> 21 22 #include "base/common.h" 23 24 namespace common { 25 26 enum ThreadFlag : uint16_t { 27 NO_FLAGS = 0 << 0, 28 SUSPEND_REQUEST = 1 << 0, 29 ACTIVE_BARRIER = 1 << 1, 30 }; 31 32 constexpr uint32_t THREAD_STATE_OFFSET = 16; 33 constexpr uint32_t THREAD_FLAGS_MASK = (0x1 << THREAD_STATE_OFFSET) - 1; 34 enum class ThreadState : uint16_t { 35 CREATED = 0, 36 RUNNING = 1, 37 NATIVE = 2, 38 WAIT = 3, 39 IS_SUSPENDED = 4, 40 TERMINATED = 5, 41 }; 42 43 union ThreadStateAndFlags { asInt(val)44 explicit ThreadStateAndFlags(uint32_t val = 0) : asInt(val) {} 45 struct { 46 volatile uint16_t flags; 47 volatile ThreadState state; 48 } asStruct; 49 struct { 50 uint16_t flags; 51 ThreadState state; 52 } asNonvolatileStruct; 53 volatile uint32_t asInt; 54 uint32_t asNonvolatileInt; 55 std::atomic<uint32_t> asAtomicInt; 56 57 private: 58 NO_COPY_SEMANTIC_CC(ThreadStateAndFlags); 59 }; 60 61 class SuspendBarrier { 62 public: SuspendBarrier()63 SuspendBarrier() : passBarrierCount_(0) {} 64 SuspendBarrier(int32_t count)65 explicit SuspendBarrier(int32_t count) : passBarrierCount_(count) {} 66 67 void Wait(); 68 69 void PassStrongly(); 70 Initialize(int32_t count)71 void Initialize(int32_t count) 72 { 73 passBarrierCount_.store(count, std::memory_order_relaxed); 74 } 75 76 private: 77 std::atomic<int32_t> passBarrierCount_; 78 }; 79 } // namespace common 80 #endif // COMMON_INTERFACES_THREAD_THREAD_STATE_H 81