Understanding stateful_actor

I read some use of stateful_actor in examples / curl / curl_fuse.cpp and libcaf_core / test / stateful_actor.cpp . It looks like stateful_actor<State> can bind some states to an actor by declaring fields in a State struct . It is very useful.

Can we declare states as fields in a class-based actor to get the same effects? Or is there some special handling in stateful_actor (e.g. access to a security thread)?

Do the characters in the following example have the same functionality?

 /* Class based actor */ struct ClassCounter : caf::event_based_actor { caf::behavior make_behavior() override { return { [=](inc_atom){ i += 1; } , [=](ret_atom){ return i; } }; } const char* name() const override { return "I am class-based"; } int i = 0; }; /* Stateful actor */ struct CounterState { caf::local_actor* self; int i = 0; const char* name = "I am stateful"; }; caf::behavior StatefulCounter(caf::stateful_actor<CounterState>* self) { return { [=](inc_atom){ self->state.i += 1; } , [=](ret_atom){ return self->state.i; } }; }; 
+5
source share
1 answer

Can we declare states as fields in a class-based actor to get the same effects? Or is there some special handling in stateful_actor (e.g. access to a security thread)?

CAF runtime assumes actors must be isolated, i.e. only the actor himself is allowed access to his state. Therefore, access to the state of an actor is never synchronized. Interactive communication uses messaging, thereby avoiding race conditions in design.

The subjects mentioned allow programmers to write fewer classes (and therefore less boilerplate code), but there is also one notable difference between ClassCounter and StatefulCounter : the lifetime of variables. In ClassCounter , member variable i lives until the ClassCounter destructor is ClassCounter . Since the actors are counted, the destructor works if there is no link to it, i.e. There is no actor or actor_addr handle for the actor. In a StatefulCounter a CounterState member is created if an actor is initialized and destroyed if it terminates.

A condition exists only as long as the actor is alive. This is especially useful for interrupting loops. If you have two members A and B , you have a loop if A contains a reference to B through a member variable and vice versa. Instead, this subject disrupts this process instead. A automatically issues its link to B when exiting and vice versa.

+5
source

Source: https://habr.com/ru/post/1238808/


All Articles