On 09.03.17 18.27, Christopher Pisz wrote:
> std::atomic<ServiceState> m_state;
[...]
> //----------------------------------------------------------------------------------------
> State::ServiceState State::GetState() const
> {
> return m_state;
> }
>
> //----------------------------------------------------------------------------------------
> void State::SetState(ServiceState state)
> {
> // TODO - Log the state change
>
> m_state = state;
> }
std::atomic is of no particular use in your code since anyone can do any
state change at any time.
Normally a state machine should control /valid/ state changes.
> int main()
> {
> State state(State::STARTED);
>
> // TODO - State can chnange between OR comparisons
> // The encapsulation of the atomic object destroyed the guarentee
> // that a comparison of an atomic with a single value would provide
Agreed. But the result is undefined anyway since the state can change
/before/ the condition as well.
> // On the otherhand, I am not sure how you would get the same behavior
> // from the atomic that you would get with
> //
> // enum State{STOPPING = 0, STOPPED, STARTING, STARTED};
> //
> // bool running = false;
> // {
> // std::lock_guard<std::mutex> lock();
> // running = (state == State::STARTED || state == State::STARTING)
> // }
#1:
State l_state = state;
running = l_state == State::STARTED || l_state == State::STARTING;
#2
running = state >= State::STARTING;
> // if( running ) { //do stuff }
> //
> if (state.GetState() == State::STARTED || state.GetState() == State::STARTING)
> {
> // Do stuff
> }
>
> As I describe in the todo before the comparison. I am thinking about wta happens when we compare with multiple values in ORed like that. One comparison occurs at a time, so we re no longer really atomic.
That's true. But it does not make any difference in your code because at
"Do stuff" state is undefined anyway since it can change at /any/ time
not just between the comparisons.
> Is there a way to get fix and still encapsulate atomic, or do we need to go back to using a lock and mutex when comparing multiple values like that?
The comparison is not your problem. The code at DoStuff probably need to
be synchronized with state changes.
Marcel