Tuesday, September 6, 2011

Timed Receive

It's not unusual to send a message and then wait for response. But if your communication partner doesn't reply, you'll wait forever. That's why we need an option to specify timeouts.

Here's a short example actor that does nothing but sends you back your own messages and exits if he idles for 10sec.

#include <chrono>
#include "cppa/cppa.hpp"

using namespace cppa;

void echo_server()
{
  receive_loop (
    others() >> []() {
      self->last_sender() << self->last_dequeued();
    },
    after(std::chrono::seconds(10)) >> []() {
      quit(exit_reason::user_defined);
    }
  );
}


The after()-statement has to be the last one and you can't specify more than one. An empty receive with nothing but a timeout should be used to sleep for a certain amount of time, e.g.:
receive(after(std::chrono::milliseconds(5)) >> []() {});

Btw: you should not use native sleep functions, because they are blocking. That's only ok if you spawned your Actor with the detached flag, because the Actor has its own thread in this case. But remember that your Actors usually share one thread pool and blocking function calls should be best avoided.

No comments:

Post a Comment