-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstate.h
67 lines (54 loc) · 1.24 KB
/
state.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#pragma once
#include "lock.h"
template <typename T>
class state_ctrl {
private:
critical_section_t cs;
T state;
public:
state_ctrl(const T initial);
~state_ctrl();
T get_state();
bool is_state (const T state);
bool transition(const T current_state, const T next_state);
void force_transition(const T next_state);
};
template <typename T>
state_ctrl<T>::state_ctrl(const T initial)
{
critical_section_init(&cs);
state = initial;
}
template <typename T>
state_ctrl<T>::~state_ctrl()
{
critical_section_deinit(&cs);
}
template <typename T>
T state_ctrl<T>::get_state()
{
lock_guard lk(&cs);
return state;
}
template <typename T>
bool state_ctrl<T>::is_state(const T state)
{
lock_guard lk(&cs);
return this->state == state;
}
template <typename T>
bool state_ctrl<T>::transition(const T current_state, const T next_state)
{
lock_guard lk(&cs);
if (state == current_state) {
state = next_state;
return true;
}
return false;
}
template <typename T>
void state_ctrl<T>::force_transition(const T next_state)
{
lock_guard lk(&cs);
state = next_state;
}