Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include "caf/all.hpp"
- using namespace caf;
- using std::endl;
- using std::vector;
- using hello_atom = atom_constant<atom("hello")>;
- // How to solve this common erlang problem:
- // > Gs = [list of actors]
- // > lists:foreach(fun (G) -> receive {G, hello} -> ok end end, Gs),
- // 1. from a scoped_actor
- // 2. from a stateful_actor
- void sender_fun(event_based_actor* self, int id, actor send_to) {
- self->send(send_to, hello_atom::value, id);
- }
- void caf_main(actor_system& system){
- scoped_actor self{system};
- int n = 5;
- auto create_senders = [&system, n] (actor to) {
- vector<actor> result;
- for (int i = 0; i < n; ++i) {
- result.emplace_back(system.spawn(sender_fun, i, to));
- }
- return result;
- };
- auto senders = create_senders(self);
- // scoped actor
- aout(self) << "##-- scoped actor --##" << endl;
- vector<actor>::const_iterator it = begin(senders);
- bool all_matched = false;
- while (!all_matched) {
- self->receive([&] (hello_atom, int id) -> result<void> {
- aout(self) << "scoped actor: received message with id: " << id << " ";
- if (actor_cast<actor>(self->current_sender()) == *it) {
- aout(self) << "ok" << endl;
- ++it;
- if (it == end(senders)) {
- aout(self) << "done, msg of all senders received" << endl;
- all_matched = true;
- }
- return unit;
- } else {
- aout(self) << "skiped" << endl;
- return skip;
- }
- });
- }
- }
- CAF_MAIN()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement