Branch data Line data Source code
1 : : // Copyright 2026 HPActor Contributors
2 : : //
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 : : #pragma once
16 : :
17 : : #include <atomic>
18 : : #include <cstdint>
19 : :
20 : : namespace hpactor {
21 : :
22 : : // ActorState: atomic state encoding for coroutine actor lifecycle
23 : : // States: Idle → Ready → Running → IOWaiting / Terminated
24 : : class ActorState {
25 : : public:
26 : : static constexpr uint32_t kIdle = 0x01;
27 : : static constexpr uint32_t kReady = 0x02;
28 : : static constexpr uint32_t kRunning = 0x04;
29 : : static constexpr uint32_t kIOWaiting = 0x08;
30 : : static constexpr uint32_t kTerminated = 0x10;
31 : : static constexpr uint32_t kMask = 0x1F;
32 : :
33 : 144 : ActorState() : state_(kIdle) {}
34 : : explicit ActorState(uint32_t initial) : state_(initial) {}
35 : :
36 : 533 : uint32_t get() const {
37 : 1066 : return state_.load(std::memory_order_acquire);
38 : : }
39 : :
40 : : // CAS transition. Returns true if successful.
41 : 485 : bool cas(uint32_t expected, uint32_t desired) {
42 : 485 : return state_.compare_exchange_strong(expected, desired,
43 : : std::memory_order_acq_rel,
44 : 485 : std::memory_order_acquire);
45 : : }
46 : :
47 : 373 : void set(uint32_t s) {
48 : 373 : state_.store(s, std::memory_order_release);
49 : 373 : }
50 : :
51 : 361 : bool is_idle() const {
52 : 361 : return get() == kIdle;
53 : : }
54 : 3 : bool is_ready() const {
55 : 3 : return get() == kReady;
56 : : }
57 : 5 : bool is_running() const {
58 : 5 : return get() == kRunning;
59 : : }
60 : 12 : bool is_io_waiting() const {
61 : 12 : return get() == kIOWaiting;
62 : : }
63 : 2 : bool is_terminated() const {
64 : 2 : return get() == kTerminated;
65 : : }
66 : :
67 : : private:
68 : : std::atomic<uint32_t> state_;
69 : : };
70 : :
71 : : } // namespace hpactor
|