Home
libcppa - boost.org
Contents
1. 00000 o 11 5 1 Implicit self Pointer 5 2 Interface 6 Sending Messages 6 1 Replying to Messages 6 2 Delaying Messages 6 3 Forwarding Messages in Untyped Actors 0 o 7 Receiving Messages 7 1 Class based actors 7 2 Nesting Receives Using become unbecoMe o 7 3 Timeouts 7 4 Skipping Messages 8 Synchronous Communication 8 1 Error Messages 8 2 Receive Response Messages 8 3 Synchronous Failures and Error Handlers 24 8 3 1 Continuations for Event based Actors 9 Management amp Error Detection 9 1 Links 9 2 Monitors 9 3 ErrorCodes 9 4 Attach Cleanup Code to an Actor 2 10 Spawning Actors 11 Message Priorities 12 Network Transparency 12 1 Publishing of Actors 12 2 Connecting to Remote Actors 12 12 13 14 15 15 16 17 17 19 20 21 22 22 23 23 24 25 25 25 26 26 27 28 13 Group Communication 13 1 Anonymous Groups 224 2242544542545 445 sob Ot Ok PES DS 13 2 Local GrOUPS 2 24 224065 268 2342 6 Soo AAA Be ow ee g 13 3 Spawn Actors in Groups 5634500324 So a oe See bee 500 0 508 508 14 Platform Independent Type System 14 1 User Defined Data Types in Messages o ee 15 Blocking AP
2. auto a0 spawn my_actorl auto al self gt spawn lt linked gt my_actor2 42 hello actor auto a2 self gt spawn lt monitored gt auto a3 spawn int 42 spawn thread mapped actors auto ad spawn lt detached gt my_actorl auto a5 self gt spawn lt detached linked gt 1 x auto a6 spawn lt detached gt my_actor2 0 zero spawn class based actors auto a7 spawn lt my_actor3 gt auto a8 self gt spawn lt my_actor4 monitored gt 42 spawn thread mapped actors using a class auto a9 spawn lt my_actor4 detached gt 42 spawn actors that need access to the blocking API auto aa self gt spawn lt blocking_api gt ugly_duckling compiler error my_actor2 captures the implicit self pointer as event_based_actorx and thus cannot be spawned using blocking_api flag x auto ab self gt spawn lt blocking_api gt my_actor2 x 21 MESSAGE PRIORITIES 11 Message Priorities By default all messages have the same priority and actors ignore priority flags Actors that should evaluate priorities must be spawned using the priority_aware flag This flag causes the actor to use a priority aware mailbox implementation It is not possible to change this implementation dynamically at runtime Fh an behavior testee event_based_actor seli send b with normal priority sel
3. i size_t received 0 size_t received 0 do do_receive receive others gt gt amp others gt gt amp received received until gref received gt 10 y while received lt 10 The examples above illustrate the correct usage of the three loops receive_loop receive_for and do_receive until ltis possible to nest receives and receive loops self gt receive_loop on lt int gt gt gt amp int valuel self gt receive on lt float gt gt gt amp float value2 cout lt lt valuel lt lt gt lt lt value2 lt lt endl 33 BLOCKING API 15 2 Receiving Synchronous Responses Analogous to sync_send then for event based actors blocking actors can use sync_send await void foo blocking_actorx self actor testee testee replies with a string to get self gt sync_send testee atom get await e const std string amp str handle str after std chrono seconds 30 gt gt amp handle error 34 STRONGLY TYPED ACTORS 16 Strongly Typed Actors Strongly typed actors provide a convenient way of defining type safe messaging interfaces Unlike untyped actorsd typed actors are not allowed to use guard expressions When calling become in a strongly typed actor all message handlers from the typed interface must be set Typed actors u
4. set handler for timeouts n 0 H Va on_sync_timeout aout lt lt timeout occured lt lt endl set response handler by using then timed_sync_send testee std chrono seconds 30 atom get then const std string str x handle str x 23 SYNCHRONOUS COMMUNICATION 8 3 1 Continuations for Event based Actors libcppa supports continuations to enable chaining of send receive statements The functions then returns a helper object offering the member function continue_with which takes a functor f without arguments After receiving a message f is invoked if and only if the received messages was handled successfully i e neither sync_failure nor sync_timeout occurred void foo event_based_actorx self replies with either a double or a string actor d_or_s sync_send d_or_s atom get then double value functor f1 x const string amp value x functor f2x continue_with this continuation is invoked in both cases xafterx fl or 2 is done but x notx in case of sync_failure or sync_timeout Y 24 MANAGEMENT amp ERROR DETECTION 9 Management amp Error Detection libcppa adapts Erlang s well established fault propagation model It allows to build actor subsys tem in which either all actors are alive or have collectively failed 9 1 Links Linked actors monitor eac
5. 14 1 User Defined Data Types in Messages All user defined types must be explicitly announced so that libcppa can de serialize them cor rectly as shown in the example below include cppa cppa hpp using namespace cppa struct foo int a int b int main announce lt foo gt amp foo a foo b foo can now safely be used in messages Without the announce function call the example program would terminate with an exception because ibcppa rejects all tyoes without available runtime type information announce takes the class as template parameter and pointers to all members or getter setter pairs as arguments This works for all primitive data types and STL compliant containers See the announce examples 1 4 of the standard distribution for more details Obviously there are limitations You have to implement serialize deserialize by yourself if your class does implement an unsupported data structure See announce_example_5 cpp in the examples folder 31 BLOCKING API 15 Blocking API Besides event based actors the default implementation libcppa also provides context switching and thread mapped actors that can make use of the blocking API Those actor implementations are intended to ease migration of existing applications or to implement actors that need to have access to blocking receive primitives for other reasons Event based actors differ in receiving messages from context swi
6. vector lt string gt strings abc def on_arg_match when _x1l front 0 gt gt const ivec amp v note we don t have to check whether _xl is empty in our guard if because _x1 front returns an option for a reference to the first element assert v size gt 1 assert v front 0 on lt int gt when _xl in 10 20 30 gt gt int i assert i 10 i 20 i 30 on lt string gt when _x1 not_in strings gt gt const string amp str assert str abc amp amp str def hy on lt string gt when _xl size 10 gt gt const string str if 10 PATTERN MATCHING 4 6 Projections and Extractors Projections perform type conversions or extract data from a given input If a callback expects an integer but the received message contains a string a projection can be used to perform a type conversion on the fly This conversion should be free of side effects and in particular shall not throw exceptions because a failed projection is not an error A pattern simply does not match if a projection failed Let us have a look at a simple example auto intproj const string str gt option lt int gt char endptr nullptr static_cast lt int gt strtol str c_str amp endptr 10 if endptr nullptr amp amp endptr 0 return result return by partial_function fun on intproj gt gt in
7. 20 any_tuple auto x4 make_any_tuple 42 any_tuple COPY ON WRITE TUPLES 3 2 Casting Tuples The function tuple_cast restores static type information from an any_tuple object It returns an option see Section 18 1 for a cow_tuple of the requested types auto xl make_any_tuple 1 2 3 auto x2_opt tuple_cast lt int int int gt x1 assert x2_opt valid auto x2 x2_opt assert get lt 0 gt x2 1 assert get lt 1 gt x2 2 assert get lt 2 gt x2 3 The function tuple_cast can be used with wildcards see Section to create a view to a subset of the original data No elements are copied unless the tuple becomes detached auto xl make_cow_tuple 1 2 3 any_tuple x2 xl auto x3_opt tuple_cast lt int anything int gt x2 assert x3_opt valid auto x3 x3_opt assert get lt 0 gt x3 1 assert get lt 1 gt x3 3 assert amp get lt 0 gt x3 amp get lt 0 gt x1 assert 8get lt 1 gt x3 amp get lt 2 gt x1 PATTERN MATCHING 4 Pattern Matching C does not provide pattern matching facilities A general pattern matching solution for arbitrary data structures would require a language extension Hence we decided to restrict our implemen tation to tuples to be able to use an internal domain specific language approach 4 1 Basics A match expression begins with a call to the function on which returns an intermediate ob
8. pr yetur pra pr b const shutdown_request quit y 36 STRONGLY TYPED ACTORS void tester event_based_actor self const calculator_type amp testee self gt link_to testee will be invoked if we receive an unexpected response message self gt on_sync_failure aout self lt lt AUT actor under test failed lt lt endl self gt quit exit_reason user_shutdown PD first test 2 1 3 self gt sync_send testee plus_request 2 1 then int r1 assert rl 3 second test 2 1 1 self gt sync_send testee minus_request 2 1 then int r2 assert r2 1 both tests succeeded aout self lt lt AUT actor under test lt lt seems to be ok lt lt endl self gt send testee shutdown_request 5 int main announce custom message types announce lt shutdown_request gt announce lt plus_request gt amp plus_request a amp plus_request b announce lt minus_request gt amp minus_request a amp minus_request b test function based impl spawn tester spawn_typed typed_calculator await_all_actors_done test class based impl spawn tester spawn_typed lt typed_calculator_class gt await_all_actors_done done shutdown return 05 37 COMMON PITFALLS 17 Common Pitfalls 17 1 Event Based API e The functions become and handle_resp
9. and non const access The template function get returns an element as immutable value while get_ref explicitly returns a mutable reference to the required value and detaches the tuple if needed We do not provide a const overload for get because this would cause to unintended and thus unnecessary copying overhead auto xl make_cow_tuple 1 2 3 cow_tuple lt int int int gt auto x2 xl com tuple lt int int 1nt gt assert 8get lt 0 gt x1 get lt 0 gt x2 point to the same data get_ref lt 0 gt x1 10 detaches x1 from x2 get lt 0 gt x1 10 compiler error assert get lt 0 gt x1 10 ff xl is now 110 2 3 assert get lt 0 gt x2 1 El 32 Te Still di 2 2 assert 8 get lt 0 gt x1 amp get lt 0 gt x2 no longer the same 3 1 Dynamically Typed Tuples The class any_tuple represents a tuple without static type information All messages send between actors use this tuple type The type information can be either explicitly accessed for each element or the original tuple or a subtuple of it can be restored using tuple_cast Users of libcppa usually do not need to know about any_tuple since it is used behind the scenes However any_tuple can be created from a cow_tuple or by using make_any_tuple as shown below auto xl make_cow_tuple 1 2 3 com_tuple lt int int int gt any_tuple x2 x1 any_tuple any_tuple x3 make_cow_tuple 10
10. by either using then event based actors or await blocking actors void foo event_based_actorx self actor testee testee replies with a string to get self gt sync_send testee atom get then on_arg_match gt gt const std string str handle str after std chrono seconds 30 gt gt handle error i y Similar to become the then function modifies an actor s behavior stack However it is used as one shot handler and automatically returns to the previous behavior afterwards 8 3 Synchronous Failures and Error Handlers An unexpected response message i e a message that is not handled by given behavior will invoke the actor s on_sync_failure handler The default handler kills the actor by calling self gt quit exit_reason unhandled_sync_failure The handler can be overridden by calling self gt on_sync_failure x Unhandled timeout messages trigger the on_sync_timeout handler The default handler kills the actor for reason exit_reason unhandled_sync_failure It is possible set both error handlers by calling self gt on_sync_timeout_or_failure void foo event_based_actorx self actor testee test replies with a string to get set handler for unexpected messages self gt on_sync_failure aout lt lt received lt lt to_string self gt last_dequeued lt lt endl y
11. code use cppa exit_reason as_string uint32_t normal 1 Actor finished execution without error unhandled_exception 2 Actor was killed due to an unhandled exception Indicates that an event based actor tried to use unallowed_function_call 3 blocking receive calls Actor was killed due to an unexpected syn unhandled_sync_failure 4 chronous response message Actor was killed because no timeout handler unhandled_sync_timeout 5 i was set and a synchronous message timed out user_shutdown 16 Actor was killed by a user generated event Indicates that a remote actor became unreach able e g due to connection error user defined 65536 Minimum value for user defined exit codes remote_link unreachable 257 9 4 Attach Cleanup Code to an Actor Actors can attach cleanup code to other actors This code is executed immediately if the actor has already exited Keep in mind that self refers to the currently running actor Thus self refers to the terminating actor and not to the actor that attached a functor to it auto worker spawn actor observer self monitor spawned actor worker gt attach_functor observer std uint32_t reason this callback is invoked from worker anon_send observer atom DONE wait until worker exited self gt become on atom DONE gt gt worker terminated i Note It is possible to attach code to remote acto
12. double gt gt gt double 1 x if OK on lt int float double gt gt gt float double 1 xr x F Ok on lt int float double gt gt gt int float double 1 ok on lt int float double gt gt gt int i x compiler error PATTERN MATCHING 4 2 Reducing Redundancy with arg match and on_arg_match Our previous examples always used the most verbose form which is quite redundant since you have to type the types twice as template parameter and as argument type for the lambda To avoid such redundancy arg_match can be used as last argument to the function on This causes the compiler to deduce all further types from the signature of the given callback on lt int int gt gt gt int a int b x is equal to on arg_match gt gt int a int b x x Note that the second version does call on without template parameters Furthermore arg_match must be passed as last parameter If all types should be deduced from the callback signature on_arg_match can be used It is equal to on arg_match However when using a pattern to initialize the behavior of an actor on_arg_match is used implicitly whenever a functor is passed without preceding it with an on clause on_arg_match gt gt const std string amp str 4 3 Atoms Assume an actor provides a mathematical service for integers It takes two arguments perf
13. lt to_string self gt last_received lt lt endl y y Note that sb_actor uses the Curiously Recurring Template Pattern Thus the derived class must be given as template parameter This technique allows sb_actor to access the init_state member of a derived class The following example illustrates a more advanced state based actor that implements a stack with a fixed maximum number of elements 17 RECEIVING MESSAGES class fixed_stack public sb_actor lt fixed_stack gt friend class sb_actor lt fixed_stack gt size_t max_size vector lt int gt data behavior full behavior filled behavior empty behavior init_state empty public fixed_stack size_t max max_size max full on atom push arg_match gt gt int discard x on atom pop gt gt gt cow_tuple lt atom_value int gt auto result data back data pop_back become filled return atom ok result 5 filled on atom push arg_match gt gt int what data push_back what 1f data size max_size become full on atom pop gt gt gt cow_tuple lt atom_value int gt auto result data back data pop_back if data empty become empty return fatom ok result i empty on atom push arg_match gt gt int what data push_back what become filled on atom pop gt gt re
14. 19 RECEIVING MESSAGES 7 3 Timeouts A behavior set by become is invoked whenever a new messages arrives If no message ever arrives the actor would wait forever This might be desirable if the actor only provides a service and should not do anything else But often we need to be able to recover if an expected messages does not arrive within a certain time period The following examples illustrates the usage of after to define a timeout include lt chrono gt include lt iostream gt include cppa cppa hpp using std endl behavior eager_actor event_based_actorx self return CAR 1 A Pe eas BF fy leat i 4 vex F Fy others gt gt 1 after std chrono seconds 10 gt gt aout self lt lt received nothing within 10 seconds lt lt endl Callbacks given as timeout handler must have zero arguments Any number of patterns can pre cede the timeout definition but after must always be the final statement Using a zero duration timeout causes the actor to scan its mailbox once and then invoke the timeout immediately if no matching message was found libcppa supports timeouts using minutes seconds milliseconds and microseconds However note that the precision depends on the operating system and your local work load Thus you should not depend on a certain clock resolution 20 RECEIVING MESSAGES 7 4 Skipping Messages Unmatched messages are skippe
15. I 15 1 Receiving Messages 15 2 Receiving Synchronous Responses o 16 Strongly Typed Actors 16 1 Spawning Typed Actors o e 16 2 Class based Typed Actors 17 Common Pitfalls 17 1 Event Based API ocios iia a 17 2 Synchronous Messages 17 3 Sending Messages 174A SHADO A ee ee eh eA ee S 17 5 Constructors of Class based Actors 18 Appendix 18 1 Class option 200 18 2 Using aout A Concurrency safe Wrapper for cout 30 30 30 30 31 31 32 32 34 35 35 36 38 38 38 38 38 38 INTRODUCTION 1 Introduction Before diving into the API of libcppa we would like to take the opportunity to discuss the concepts behind libcppa and to explain the terminology used in this manual 1 1 Actor Model The actor model describes concurrent entities actors that do not share state and communicate only via message passing By decoupling concurrently running software components via message passing the actor model avoids race conditions by design Actors can create spawn new actors and monitor each other to build fault tolerant hierarchical systems Since message passing is network transparent the actor model applies to both concurrency and distribution When dealing with dozens of cores mutexes semaphores and other threading primitives are the wrong le
16. c_timeout auto fun Sets a handler i e a functor taking no ar guments for timed_sync_send timeout mes sages default action is to kill the actor for reason unhandled_sync_timeout void monitor actor_ptr whom Adds a unidirectional monitor to whom see Section void demonitor actor_ptr whom Removes a monitor from whom bool has_sync_failure_handler Checks wheter this actor has a user defined sync fail ure handler 13 SENDING MESSAGES 6 Sending Messages Messages can be sent by using the member function send or send_tuple The variadic tem plate function send has the following signature template lt typename Args gt void send actor whom Args amp amp what The variadic template pack what is converted to a dynamically typed tuple see Section 3 1 and then enqueued to the mailbox of whom Using the function send is more compact but does not have any other benefit However note that you should not use send if you already have an instance of any_tuple because it creates a new tuple containing the old one void some_fun event_based_actorx self actor other spawn auto msg make_any_tuple 1 2 3 self gt send other msg oops creates a new tuple containing msg self gt send_tuple other msg ok 14 SENDING MESSAGES 6 1 Replying to Messages The return value of a message handler is used as response message Actors can also use the result of a
17. d and define their message pass ing interface as list of replies_to lt gt with lt gt statements This interface is used in 1 typed_event_based_actor lt gt which is the base class for typed actors 2 the han dle type typed_actor lt gt and 3 typed_behavior lt gt i e the behavior definition for typed actors Since this is rather redundant the actor handle provides definitions for the behavior as well as the base class as shown in the example below It is worth mentioning that all typed actors always use the event based implementation i e there is no typed actor implementation providing a blocking API n truct shutdown_request truct plus_request int a int b truct minus_request int a int b n 10 typedef typed_actor lt replies_to lt plus_request gt with lt int gt replies_to lt minus_request gt with lt int gt replies_to lt shutdown_request gt with lt void gt gt calculator_type calculator_type behavior_type typed_calculator calculator_type pointer self return const plus_request amp pr return pr a pr b hy const minus_request amp pr return pr a pr b hy const shutdown_request self gt quit class typed_calculator_class public calculator_type base protected behavior_type make_behavior override return const plus_request amp pr return pr a pr b 7 const minus_request amp
18. d automatically by libcppa s runtime system This is true for all actor implementations To allow actors to skip messages manually skip_message can be used This is in particular useful whenever an actor switches between behaviors but wants to use a default rule created by others to filter messages that are not handled by any of its behaviors The following example illustrates a simple server actor that dispatches requests to workers Af ter receiving an idle message it awaits a request that is then forwarded to the idle worker Afterwards the server returns to its initial behavior i e awaits the next idle message The server actor will exit for reason user_defined whenever it receives a message that is neither a request nor an idle message behavior server event_based_actorx self auto die self gt quit exit_reason user_defined return on atom idle gt gt auto worker last_sender self gt become keep_behavior on atom request gt gt forward request to idle worker self gt forward_to worker await next idle message self gt unbecome 7 on atom idle gt gt skip_message others gt gt die i 7 on atom request gt gt skip_message others gt gt die y 21 SYNCHRONOUS COMMUNICATION 8 Synchronous Communication libcppa supports both asynchronous and synchronous communication The member function
19. d to opt out of this cooperative scheduling 5 1 Implicit self Pointer When using a function or functor to implement an actor the first argument can be used to capture a pointer to the actor itself The type of this pointer is event_based_actor per default and blocking_actorx when using the blocking_api flag When dealing with typed actors the types are typed_event_based_actor lt gt x and typed_blocking_actor lt gt x 12 ACTORS 5 2 Interface class local_actor Member functions quit uint32_t reason normal Finishes execution of this actor Observers bool trap_exit Checks whether this actor traps exit messages any_tuple last_dequeued Returns the last message that was dequeued from the actor s mailbox Note Only set during callback invocation actor_addr last_sender Returns the sender of the last dequeued message Note Only set during callback invocation vector lt group gt joined_groups Returns all subscribed groups Modifiers void trap_exit bool enabled Enables or disables trapping of exit messages void join const group g Subscribes to group g void leave const group g Unsubscribes group g void on_sync_failure auto fun Sets a handler i e a functor taking no argu ments for unexpected synchronous response mes sages default action is to kill the actor for reason unhandled_sync_failure void on_syn
20. e result lr lt reply X handle response Kasi X The forwarding is completely transparent to actor C since it will see actor A as sender of the message However actor A will see actor C as sender of the response message instead of actor B and thus could recognize the forwarding by evaluating self gt last_sender 16 RECEIVING MESSAGES 7 Receiving Messages The current behavior of an actor is its response to the next incoming message and includes a sending messages to other actors b creation of more actors and c setting a new behavior An event based actor i e the default implementation in ibcppa uses become to set its behavior The given behavior is then executed until it is replaced by another call to become or the actor finishes execution 7 1 Class based actors A class based actor is a subtype of event_based_actor and must implement the pure virtual member function make_behavior returning the initial behavior class printer public event_based_actor behavior make_behavior override return others gt gt cout lt lt to_string last_received lt lt endl Another way to implement class based actors is provided by the class sb_actor State Based Actor This base class simply returns init_state defined in the subclass from its implemen tation for make_behavior struct printer sb_actor lt printer gt behavior init_state others gt gt cout lt
21. e_actor const charx host std uintl6_t port The function remote_actor connects to the actor at given host and port A network_error is thrown if the connection failed auto pong remote_actor localhost 4242 self gt send pong atom ping 0 self gt become on atom pong 10 gt gt sel f gt quit on atom pong arg_match gt gt int i return make_cow_tuple atom ping itl 29 GROUP COMMUNICATION 13 Group Communication libcppa supports publish subscribe based group communication Actors can join and leave groups and send messages to groups std string group_module std string group_id auto grp group get group_module group_id self gt join grp self gt send grp atom test self gt leave grp 13 1 Anonymous Groups Groups created on the fly with group anonymous can be used to coordinate a set of work ers Each call to group anonymous returns a new unique group instance 13 2 Local Groups The local group module creates groups for in process communication For example a group for GUI related events could be identified by group get local GUI events The group ID GUI events uniquely identifies a singleton group instance of the module local 13 3 Spawn Actors in Groups The function spawn_in_group can be used to create actors as members of a group The function causes the newl
22. eck message types statically 1 2 5 Spawning Spawning an actor means to create and run a new actor 1 2 6 Monitoring A monitored actor sends a down message to all actors monitoring it as part of its termination This allows actors to supervise other actors and to take measures when one of the supervised actors failed i e terminated with a non normal exit reason 1 2 7 Link A link is bidirectional connection between two actors Each actor sends an exit message to all of its links as part of its termination Unlike down messages cf 1 2 6 the default behavior for received exit messages causes the receiving actor to terminate for the same reason if the link has failed i e terminated with a non normal exit reason This allows developers to create a set of actors with the guarantee that either all or no actors are alive The default behavior can be overridden i e exit message can be trapped When trapping exit messages they are received as any other ordinary message and can be handled by the actor FIRST STEPS 2 First Steps To compile ibcppa you will need CMake and a C 11 compiler To get and compile the sources open a terminal on Linux or Mac OS X and type git clone git github com Neverlord libcppa git cd libcppa configure make make install as root optional It is recommended to run the unit tests as well make test Please submit a bug report that includes a your compiler
23. f gt send self atom b send ta with high priority self gt send message_priority high self atom a terminate after receiving a b return on atom b gt gt aout self lt lt received b gt quit lt lt endl self gt quit r on atom a gt gt aout self lt lt received a lt lt endl Fy int main i WLLL print spawn testee await_all_act eT received b gt quit Se ors_done ct will print received a and then received b gt quit spawn lt priority_aware gt testee await_all_actors_done shutdown 28 NETWORK TRANSPARENCY 12 Network Transparency All actor operations as well as sending messages are network transparent Remote actors are represented by actor proxies that forward all messages 12 1 Publishing of Actors void publish actor whom std uint16_t port const char addr 0 The function publish binds an actor to a given port It throws network_error if socket related errors occur or bind_failure if the specified port is already in use The optional addr param eter can be used to listen only to the given IP address Otherwise the actor accepts all incoming connections INADDR_ANY publish self 4242 self gt become on atom ping arg_match gt gt int i return make_cow_tuple atom pong 1 i 12 2 Connecting to Remote Actors actor remot
24. h other An actor sends an exit message to all of its links as part of its termination The default behavior for actors receiving such an exit message is to die for the same reason if the exit reason is non normal Actors can trap exit messages to handle them manually actor worker receive exit messages as regular messages self gt trap_exit true monitor spawned actor self gt link_to worker wait until worker exited self gt become const exit_msg amp e gt gt if e reason exit_reason normal worker finished computation else worker died unexpectedly 9 2 Monitors A monitor observes the lifetime of an actor Monitored actors send a down message to all ob servers as part of their termination Unlike exit messages down messages are always treated like any other ordinary message An actor will receive one down message for each time it called self gt monitor even if it adds a monitor to the same actor multiple times actor worker monitor spawned actor self gt monitor worker wait until worker exited self gt become on const down_msg d gt gt if d reason exit_reason normal worker finished computation else worker died unexpectedly 25 MANAGEMENT amp ERROR DETECTION 9 3 Error Codes All error codes are defined in the namespace cppa exit_reason To obtain a string repre sentation of an error
25. ject providing the member function when and operator gt gt The right hand side of the operator denotes a callback usually a lambda expression that should be invoked if a tuple matches the types given to on as shown in the example below on lt int gt gt gt int i x x on lt ink loat gt 0 gt gt ame 1 loat El Jrasak 4 on lt int int int gt gt gt int a int b int c The result of operator gt gt is a match statement A partial function can consist of any number of match statements At most one callback is invoked since the evaluation stops at the first match partial_function fun on lt int gt gt gt int i casel ty on lt int gt gt gt int i case2 never invoked since casel always matches first y The function on can be used in two ways Either with template parameters only or with function parameters only The latter version deduces all types from its arguments and matches for both type and value To match for any value of a given type val can be used as shown in the following example on 42 gt gt int i assert i 42 on hello world gt gt x on print val lt std string gt gt gt const std string amp what Lt Note The given callback can have less arguments than the pattern But it is only allowed to skip arguments from left to right on lt int float
26. l other actors we ve spawned are done await_all_actors_done done shutdown return 0 40
27. libcppa A C library for actor programming User Manual libcppa version 0 9 0 PRERELEASE Dominik Charousset March 18 2014 Contents 1 1 Actor MOOG a o sene saa Bee Bee Rae A De SER EL AAA eS a 1 ee ermiNOIOgY sz sa Ree ee er See Dare Ee EL ee AAA A S 1 1 2 1 Actor Address lt 2 Spe ogg op do ig eh ee a ow a Oe SS wae 1 Sete ees a Oe a eda eek ss a ES 2 1 23 Untyped ACTOS sab fe eb awed Se aed ere Be oh eh Oe ee 2 1 24 VOC ACTOT ed se de eed ek eB ek ae de ee E 2 1 2 0 Spawning 2 hos 4 4 54 25 a ee ca Se eee eS oad 2 1 2 6 Monitoring lt bes ne eben ee eb ea beh ban eee deh ed 2 T2 ENR ose shee he Se eet eb eebt ehh iSSibG44 488 HS 2 3 2 1 Features Overview bs he wee wee eS SES SHES EERE ES 3 2 2 Supported Compllers 2 2 4 25 22 ee ee lt ee 3 2 3 Supported Operating Systems 0 0000 eee ee 3 ete fe Be Re e eee o ee Be oe ae Be Oe 4 5 3 1 Dynamically Typed Tuples sio ss eae ee a a 5 3 2 Casting TUpIES 4 2 5 2285005 pa 8 4 doa 80 4 808 a a a eoe g ER AR wakes 6 4 Pattern Matching 7 4 1 BASICOS aoaaa a 7 4 2 Reducing Redundancy with arg match and on_arg_match 8 43 AtOMS oo be Doe GSE e aaa de se 8 44 WildcardS era aaa 9 AO GUMS ay 2 4 a a be obs IN 9 4 5 1 Placeholder Interface ee ee 10 4 5 2 Examples for Guard Expressions 0 0 10 4 6 Projections and ExtractorS
28. llo_world event_based_actorx self const actorg buddy send Hello World to our buddy buddy Hello World then self gt sync_send EF naa MALE const string what IF sss and print TE aout self lt lt what int main for a response t t lt lt endl create a new actor that calls mirror auto mirror_actor spawn create another actor that calls hello world mirror actor spawn hello_world mirror_actor wait until all await_all_actors_done run cleanup code before exiting main shutdown mirror other actors we have spawned are done COPY ON WRITE TUPLES 3 Copy On Write Tuples The message passing implementation of ibcppa uses tuples with call by value semantic Hence it is not necessary to declare message types though ibcppa allows users to use user defined types in messages see Section 14 1 A call by value semantic would cause multiple copies of a tuple if it is send to multiple actors To avoid unnecessary copying overhead libcppa uses a copy on write tuple implementation A tuple is implicitly shared between any number of actors as long as all actors demand only read access Whenever an actor demands write access it has to copy the data first if more than one reference to it exists Thus race conditions cannot occur and each tuple is copied only if necessary The interface of cow_tuple strictly distinguishes between const
29. onse do not block i e always return imme diately Thus one should always capture by value in lambda expressions because all references on the stack will cause undefined behavior if the lambda expression is executed 17 2 Synchronous Messages e A handle returned by sync_send represents exactly one response message Therefore it is not possible to receive more than one response message e The handle returned by sync_send is bound to the calling actor It is not possible to transfer a handle to a response to another actor 17 3 Sending Messages e send whom isdefined as send_tuple whom make_any_tuple Hence a message sent via send whom self gt last_dequeued will not yield the expected result since it wraps sel f gt last_dequeued into another any_tuple instance The correct way of forwarding messages is self gt forward_to whom 17 4 Sharing e Itis strongly recommended to not share states between actors In particular no actor shall ever access member variables or member functions of another actor Accessing shared memory segments concurrently can cause undefined behavior that is incredibly hard to find and debug However sharing data between actors is fine as long as the data is immutable and its lifetime is guaranteed to outlive all actors The simplest way to meet the lifetime guarantee is by storing the data in smart pointers such as std shared_ptr Neverthe less the recommended way of sharing informa
30. orms a predefined operation and returns the result It cannot determine an operation such as multiply or add by receiving two operands Thus the operation must be encoded into the message The Erlang programming language introduced an approach to use non numerical constants so called atoms which have an unambiguous special purpose type and do not have the runtime overhead of string constants Atoms are mapped to integer values at compile time in libcppa This map ping is guaranteed to be collision free and invertible but limits atom literals to ten characters and prohibits special characters Legal characters are _0 9A Za z and the whitespace character Atoms are created using the constexpr function atom as the following example illustrates on atom add arg_match gt gt int a int b x x x on atom multiply arg_match gt gt int a int b x x x Fp es Note The compiler cannot enforce the restrictions at compile time except for a length check The assertion atom atom is not true because each invalid character is mapped to the whitespace character PATTERN MATCHING 4 4 Wildcards The type anything can be used as wildcard to match any number of any types A pattern created by on lt anything gt or its alias others is useful to define a default case For patterns defined without template parameters the constexpr value any_vals can be used as function argument The constan
31. out When using cout from multiple actors output often appears interleaved Moreover using cout from multiple actors and thus from multiple threads in parallel should be avoided regardless since the standard does not guarantee a thread safe implementation By replacing std cout with cppa aout actors can achieve a concurrency safe text out put The header cppa cppa hpp also defines overloads for std endl and std flush for aout but does not support the full range of ostream operations yet Each write operation to aout sends a message to a hidden actor keep in mind sending messages from actor construc tors is not safe This actor only prints lines unless output is forced using flush The example below illustrates printing of lines of text from multiple actors in random order include lt chrono gt include lt cstdlib gt include lt iostream gt include cppa cppa hpp using namespace cppa using std endl int main std srand std time 0 for int i 1 i lt 50 i spawn lt blocking_api gt i blocking_actorx self aout self lt lt Hi there This is actor nr lt lt i lt lt lt lt endl std chrono milliseconds tout std rand 1000 self gt delayed_send self tout atom done self gt receive others gt gt i self aout self lt lt Actor nr lt lt i lt lt says goodbye lt lt endl wait until al
32. ress In libcppa each actor has a network wide unique logical address that can be used to identify and monitor it However the address can not be used to send a message to an actor This limitation is due to the fact that the address does not contain any type information about the actor Hence it would not be safe to send it any message because the actor might use a strictly typed messaging interface not accepting the given message INTRODUCTION 1 2 2 Actor Handle An actor handle contains the address of an actor along with its type information In order to send an actor a message one needs to have a handle to it the address alone is not sufficient The distinction between handles and addresses which is unique to libcopa when comparing it to other actor systems is a consequence of the design decision to support both untyped and typed actors 1 2 3 Untyped Actors An untyped actor does not constrain the type of messages it receives i e a handle to an untyped actor accepts any kind of message That does of course not mean that untyped actors must handle all possible types of messages Choosing typed vs untyped actors is mostly a matter of taste Untyped actors allow developers to build prototypes faster while typed actors allow the compiler to fetch more errors at compile time 1 2 4 Typed Actor A typed actor defines its messaging interface i e both input and output types in its type This allows the compiler to ch
33. rs but the cleanup code will run on the local machine 26 SPAWNING ACTORS 10 Spawning Actors Actors are created using the function spawn The easiest way to implement actors is to use func tors e g a free function or lambda expression The arguments to the functor are passed to spawn as additional arguments The function spawn also takes optional flags as template parameter The flag detached causes spawn to create a thread mapped actor opt out of the cooperative scheduling the flag Linked links the newly created actor to its parent not available on top level spawn and the flag monitored automatically adds a monitor to the new actor Actors that make use of the blocking API see Section 15 must be spawned using the flag blocking_api Flags are concatenated using the operator as shown in the examples below include cppa cppa hpp using namespace cppa void my_actorl void my_actor2 event_based_actorx int argl const std string amp arg2 void ugly_duckling class my_actor3 public event_based_actor x class my_actor4 public sb_actor lt my_actor4 gt public my_actor4 int some_value PR sas RE y whenever we want to link to or monitor a spawned actor we have to spawn it using the self pointer otherwise we can use the free function spawn top level spawn void server event_based_actorx self spawn function based actors
34. s sync_send and sync_send_tuple send synchronous request messages template lt typename Args gt __unspecified__ sync_send actor_ptr whom Args amp amp what __unspecified__ sync_send_tuple actor_ptr whom any_tuple what template lt typename Duration typename Args gt __unspecified__ timed_sync_send actor_ptr whom Duration timeout Args amp amp what template lt typename Duration typename Args gt __unspecified__ timed_sync_send_tuple actor_ptr whom Duration timeout any_tuple what A synchronous message is sent to the receiving actor s mailbox like any other asynchronous message The response message on the other hand is treated separately The difference between sync_send and timed_sync_send is how timeouts are handled The behavior of sync_send is analogous to send i e timeouts are specified by using after statements see 7 3 When using timed_sync_send function after statements are ignored and the actor will receive a sync_timeout_msg after the given duration instead 8 1 Error Messages When using synchronous messaging libcppa s runtime environment will send e if the receiver is not alive sync_exited_msg actor_addr source std uint32_t reason e if a message send by timed_sync_send timed out sync_timeout_msg 22 SYNCHRONOUS COMMUNICATION 8 2 Receive Response Messages When sending a synchronous message the response handler can be passed
35. se handles of type typed_actor lt gt rather than actor whereas the template parameters hold the messaging interface For example an actor responding to two integers with a dobule would use the type typed_actor lt replies_to lt int int gt with lt double gt gt All functions for message passing linking and monitoring are overloaded to accept both types of actors 16 1 Spawning Typed Actors Typed actors are spawned using the function spawn_typed The argument to this function call must be a match expression as shown in the example below because the runtime of libcppa needs to evaluate the signature of each message handler auto pO spawn_typed on_arg_match gt gt int a int b return static_cast lt double gt a x b on_arg_match gt gt double a double b return make_cow_tuple a b a b y assign to identical type using full_type typed_actor_ptr lt replies_to lt int int gt with lt double gt replies_to lt double double gt with lt double double gt gt full_type pl p0 assign to subtype using subtypel typed_actor_ptr lt replies_to lt int int gt with lt double gt gt subtypel p2 pod assign to another subtype using subtype2 typed_actor_ptr lt replies_to lt double double gt with lt double double gt gt subtype2 p3 p0 35 STRONGLY TYPED ACTORS 16 2 Class based Typed Actors Typed actors are spawned using the function spawn_type
36. sync_send to answer to a request as shown below void client event_based_actorx self const actor amp master become on foo arg_match gt gt const string amp request gt string return self gt sync_send master atom bar request then on_arg_match gt gt const std string amp response return response 6 2 Delaying Messages Messages can be delayed e g to implement time based polling strategies by using one of delayed_send delayed_send_tuple delayed_reply or delayed_reply_tuple The following example illustrates a polling strategy using delayed_send behavior poller event_based_actorx self self gt delayed_send self std chrono seconds 1 atom poll return on atom poll gt gt poll a resource ER schedule next polling self gt delayed_send self std chrono seconds 1 atom poll 15 SENDING MESSAGES 6 3 Forwarding Messages in Untyped Actors The member function forward_to forwards the last dequeued message to an other actor For warding a synchronous message will also transfer responsibility for the request i e the receiver of the forwarded message can reply as usual and the original sender of the message will receive the response The following diagram illustrates forwarding of a synchronous message from actor B to actor C A B sync_send gt forward_to gt x N comput
37. t any_vals is of type anything and is nothing but syntactic sugar for defining patterns on lt int anything gt gt gt int i tuple with int as first element Py on any_vals arg_match gt gt int i tuple with int as last element on any_vals arg_match is equal to on anything arg_match others gt gt everything else default handler others is equal to on lt anything gt and on any_vals 4 5 Guards Guards can be used to constrain a given match statement by using placeholders as the following example illustrates using namespace cppa placeholders contains _x1 _x9 on lt int gt when _xl 2 0 gt gt int is even hy on lt int gt gt gt int is odd Guard expressions are a lazy evaluation technique The placeholder _ x1 is substituted with the first value of a given tuple All binary comparison and arithmetic operators are supported as well as amp amp and In addition there are three functions designed to be used in guard expressions gref guard reference gval guard value and gca11 guard function call The function gref creates a reference wrapper while gval encloses a value It is similar to std ref but it is always const and lazy A few examples to illustrate some pitfalls int val 42 on lt int gt when _x1 val 7 1 matches if _xl 42 on lt int gt when _
38. t i case 1 successfully converted a string int result by on_arg_match gt gt const string amp str case 2 str is not an integer The lambda intprojis a string gt int projection but note that it does not return an integer It returns option lt int gt because the projection is not guaranteed to always succeed An empty option indicates that a value does not have a valid mapping to an integer A pattern does not match if a projection failed Note Functors used as projection must take exactly one argument and must return a value The types for the pattern are deduced from the functor s signature If the functor returns an option lt T gt then T is deduced 11 ACTORS 5 Actors libcppa provides several actor implementations each covering a particular use case The class local_actor is the base class for all implementations except for remote proxy actors Hence local_actor provides a common interface for actor operations like trapping exit messages or finishing execution The default actor implementation in libcppa is event based Event based actors have a very small memory footprint and are thus very lightweight and scalable Context switching actors are used for actors that make use of the blocking API see Section 15 but do not need to run in a separate thread Context switching and event based actors are scheduled cooperatively in a thread pool Thread mapped actors can be use
39. tching and thread mapped ac tors the former define their behavior as a message handler that is invoked whenever a new messages arrives in the actor s mailbox by using become whereas the latter use an explicit blocking receive function 15 1 Receiving Messages The function receive sequentially iterates over all elements in the mailbox beginning with the first It takes a partial function that is applied to the elements in the mailbox until an element was matched by the partial function An actor calling receive is blocked until it successfully dequeued a message from its mailbox or an optional timeout occurs self gt receiv on lt int gt when _xl gt 0 gt gt i The code snippet above illustrates the use of receive Note that the partial function passed to receive is a temporary object at runtime Hence using receive inside a loop would cause creation of a new partial function on each iteration ibcopa provides three predefined receive loops to provide a more efficient but yet convenient way of defining receive loops 32 BLOCKING API DON T DO For 33 receive_loop receive ae y y std vector lt int gt results std vector lt int gt results for size_t i 0 i lt 10 i size t i 0 receive receive_for i 10 on lt int gt gt gt amp int value on lt int gt gt gt amp int value results push_back value results push_back value
40. tions is message passing Sending data to multiple actors does not necessarily result in copying the data several times Read Section 3 to learn more about ibcppa s copy on write optimization for tuples 17 5 Constructors of Class based Actors e You should not try to send or receive messages in a constructor or destructor because the actor is not fully initialized at this point 38 APPENDIX 18 Appendix 18 1 Defined Class option in header cppa option hpp template lt typename T gt class option Represents an optional value Member types Member type Definition type T Member functions option Constructs an empty option option T value Initializes this with value option const options option option amp amp Copy move construction option amp operator const option option amp operator option amp amp Copy move assignment Observers bool expli valid cit operator bool Returns true if this has a value poe bool empty operator Returns true if this does not has a value const const T get T amp operator Access stored value const T get_or_else const T amp x Returns get if valid x otherwise Modifiers T amp ge t T operators Access stored value 39 APPENDIX 18 2 Using aout A Concurrency safe Wrapper for c
41. turn atom failure y 18 RECEIVING MESSAGES 7 2 Nesting Receives Using become unbecome Since become does not block an actor has to manipulate its behavior stack to achieve nested receive operations An actor can set a new behavior by calling become with the keep_behavior policy to be able to return to its previous behavior later on by calling unbecome as shown in the example below receives int float sequences behavior testee event_based_actorx self return int valuel self gt become the keep_behavior policy stores the current behavior on the behavior stack to be able to return to this behavior later on by calling unbecome keep_behavior float value2 cout lt lt valuel lt lt gt lt lt value2 lt lt endl restore previous behavior self gt unbecome An event based actor finishes execution with normal exit reason if the behavior stack is empty after calling unbecome The default policy of become is discard_behavior that causes an actor to override its current behavior The policy flag must be the first argument of become Note the message handling in ibcppa is consistent among all actor implementations unmatched messages are never implicitly discarded if no suitable handler was found Hence the order of arrival is not important in the example above This is unlike other event based implementations of the actor model such as Akka for instance
42. vel of abstraction Implementing applications on top of those primitives has proven challenging and error prone Additionally mutex based implementations can cause queueing and unmindful access to even distinct data from separate threads in parallel can lead to false sharing both decreasing performance significantly up to the point that an application actually runs slower when adding more cores The actor model has gained momentum over the last decade due to its high level of abstraction and its ability to make efficient use of multicore and multiprocessor machines However the actor model has not yet been widely adopted in the native programming domain With ibcppa we contribute a library for actor programming in C as open source software to ease native development of concurrent as well as distributed systems In this regard ibcppa follows the C philosophy building the highest abstraction possible without sacrificing performance 1 2 Terminology You will find that ibcppa has not simply adopted exiting implementations based on the actor model such as Erlang or the Akka library Instead libcppa aims to provide a modern C API allowing for type safe as well as dynamically typed messaging Hence most aspects of our system are familiar to developers having experience with other actor systems but there are also slight differences in terminology However neither libcppa nor this manual require any foreknowledge 1 2 1 Actor Add
43. version b your OS and c the content of the file build Testing Temporary LastTest logif an error occurs 2 1 Features Overview Lightweight fast and efficient actor implementations Network transparent messaging Error handling based on Erlang s failure model Pattern matching for messages as internal DSL to ease development Thread mapped actors for soft migration of existing applications Publish subscribe group communication 2 2 Supported Compilers e GCC gt 4 7 e Clang gt 3 2 2 3 Supported Operating Systems e Linux e Mac OS X e Note for MS Windows libcppa relies on C 11 features such as variadic templates We will support this platform as soon as Microsofts compiler implements all required C 11 features FIRST STEPS 2 4 Hello World Example include lt string gt include lt iostream gt include cppa cppa hpp using namespace std using namespace cppa behavior mirror event_based_actor self teturn the initial return actor behavior a handler for messages containing a single string that replies with a string const si tring amp what 7 prim thread sal t gt string ts Hello World via aout fe cout wrapper aout self lt lt what terminates this actor become sel f gt quit reply dlroW olien return string what rbegin what rend t lt lt endl otherwise loops forever void he
44. x1 gref val 2 matches if _xl val on lt int gt when _xl std ref val 3 ok because of placeholder others when gref val 42 4 matches everything as long as val 42 others when std ref val 42 5 compiler error PATTERN MATCHING Statement 5 is evaluated immediately and returns a boolean whereas statement 4 creates a valid guard expression Thus you should always use gref instead of std ref to avoid errors The second function gcal1 encapsulates a function call lts usage is similar to std bind but there is also a short version for unary functions gcall fun _x1 is equal to __x1 fun auto vec_sorted const std vector lt int gt amp vec return std is_sorted vec begin vec end on lt std vector lt int gt gt when gcall vec_sorted _x1 is equal to on lt std vector lt int gt gt when _x1 vec_sorted 4 5 1 Placeholder Interface template lt int X gt struct guard placeholder Member functions x represents the value at runtime y represents an iterable container size Returns x size empty Returns x empty not_empty Returns x empty front Returns an option see Section 18 1 to x front in y Returns true if y contains x false otherwise not_in y Returns in y 4 5 2 Examples for Guard Expressions using namespace std typedef vector lt int gt ivec
45. y created actors to call self gt join immediately and before spawn_in_group returns The usage of spawn_in_group is equal to spawn except for an additional group argument The group handle is always the first argument as shown in the exam ples below void funl void fun2 int float class my_actorl event_based_actor x class my_actor2 event_based_actor ce my_actor2 const std string amp str asa Pi auto grp group get auto al spawn_in_group grp funl auto a2 spawn_in_group grp fun2 1 2 0f auto a3 spawn_in_group lt my_actorl gt grp auto a4 spawn_in_group lt my_actor2 gt grp hello my_actor2 30 PLATFORM INDEPENDENT TYPE SYSTEM 14 Platform Independent Type System libcppa provides a fully network transparent communication between actors Thus libcppa needs to serialize and deserialize messages Unfortunately this is not possible using the RTTI system of C libcppa uses its own RTTI based on the class uniform_type_info since it is not possible to extend std type_info Unlike std type_info name uniform_type_info name is guaranteed to return the same name on all supported platforms Furthermore it allows to create an instance of a type by name creates a signed 32 bit integer cppa object i cppa uniform_typeid lt int gt gt create However you should rarely if ever need to use object or uniform_type_info
Download Pdf Manuals
Related Search
Related Contents
34309 AE table fan IM L-O .indd 6. Updates to the Network 4.6.1.1 User Guide - fluxus Samsung DW5000H Dish Washer with Flexible Loading User Manual Operation-Manual-Mini バイオキャブの取扱説明書はこちら Solar User Manual - Impact Recovery Systems Copyright © All rights reserved.
Failed to retrieve file