Advertisement
Guest User

Untitled

a guest
Feb 27th, 2017
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.47 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. #include <vector>
  4. #include "caf/all.hpp"
  5.  
  6. using namespace caf;
  7. using std::endl;
  8. using std::vector;
  9.  
  10. using hello_atom = atom_constant<atom("hello")>;
  11.  
  12. // How to solve this common erlang problem:
  13. // > Gs = [list of actors]
  14. // > lists:foreach(fun (G) -> receive {G, hello} -> ok end end, Gs),
  15. // 1. from a scoped_actor
  16. // 2. from a stateful_actor
  17.  
  18. void sender_fun(event_based_actor* self, int id, actor send_to) {
  19. self->send(send_to, hello_atom::value, id);
  20. }
  21.  
  22. void caf_main(actor_system& system){
  23. scoped_actor self{system};
  24. int n = 5;
  25. auto create_senders = [&system, n] (actor to) {
  26. vector<actor> result;
  27. for (int i = 0; i < n; ++i) {
  28. result.emplace_back(system.spawn(sender_fun, i, to));
  29. }
  30. return result;
  31. };
  32. auto senders = create_senders(self);
  33. // scoped actor
  34. aout(self) << "##-- scoped actor --##" << endl;
  35. vector<actor>::const_iterator it = begin(senders);
  36. bool all_matched = false;
  37. while (!all_matched) {
  38. self->receive([&] (hello_atom, int id) -> result<void> {
  39. aout(self) << "scoped actor: received message with id: " << id << " ";
  40. if (actor_cast<actor>(self->current_sender()) == *it) {
  41. aout(self) << "ok" << endl;
  42. ++it;
  43. if (it == end(senders)) {
  44. aout(self) << "done, msg of all senders received" << endl;
  45. all_matched = true;
  46. }
  47. return unit;
  48. } else {
  49. aout(self) << "skiped" << endl;
  50. return skip;
  51. }
  52. });
  53. }
  54. }
  55.  
  56. CAF_MAIN()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement