libcaf
0.13.2
|
Blocking functions to receive messages. More...
Blocking functions to receive messages.
The blocking API of libcaf is intended to be used for migrating previously threaded applications. When writing new code, you should use ibcafs nonblocking become/unbecome API.
The function send
can be used to send a message to an actor. The first argument is the receiver of the message followed by any number of values:
The function receive
takes a behavior
as argument. The behavior is a list of { pattern >> callback } rules.
Please read the manual for further details about pattern matching.
Atoms are a nice way to add semantic informations to a message. Assuming an actor wants to provide a "math sevice" for integers. It could provide operations such as addition, subtraction, etc. This operations all have two operands. Thus, the actor does not know what operation the sender of a message wanted by receiving just two integers.
Example actor:
Previous examples using receive
create behaviors on-the-fly. This is inefficient in a loop since the argument passed to receive is created in each iteration again. It's possible to store the behavior in a variable and pass that variable to receive. This fixes the issue of re-creation each iteration but rips apart definition and usage.
There are four convenience functions implementing receive loops to declare behavior where it belongs without unnecessary copies: receive_loop,
receive_while,
receive_for
and do_receive
.
receive_loop
is analogous to receive
and loops "forever" (until the actor finishes execution).
receive_while
creates a functor evaluating a lambda expression. The loop continues until the given lambda returns false
. A simple example:
receive_for
is a simple ranged-based loop:
do_receive
returns a functor providing the function until
that takes a lambda expression. The loop continues until the given lambda returns true. Example:
The function delayed_send
provides a simple way to delay a message. This is particularly useful for recurring events, e.g., periodical polling. Usage example:
See also the dancing kirby example.