Boost logo

Boost :

Subject: [boost] Interest in an Active Object CRTP "decorator"?
From: Dean Michael Berris (mikhailberis_at_[hidden])
Date: 2008-11-08 10:56:49


Hi Guys,

I've recently been working a lot with Active Object implementations.
Basically it's an instance of a class that has asynchronous operations
scheduled to be executed in its own thread of execution. I'm posting
(in-line) a very simple implementation of a CRTP "active object
enabler".

Any interest in something like this to be included in Boost?

--->8--
[NOTE: untested, licensed under the Boost Software License,
Copyright 2008 Dean Michael Berris]

template <class Derived>
struct active {
  private:
    shared_ptr<io_service> queue;
    shared_ptr<io_service::work> sentinel;
    shared_ptr<thread> lifetime_thread;

  protected:
    active() :
    queue(new io_service()),
    sentinel(new io_service::work(*queue)),
    lifetime_thread(new thread(bind(&io_service::run, queue)))
    {
      static_cast<Derived*>->init();
    };

    ~active() {
      sentinel.reset();
      lifetime_thread->join();
      static_cast<Derived*>->destroy();
    };

    void post(function<void()> f) {
      queue->post(f);
    };

};

--->8--

Example usage would be something like this:

--->8--

struct logger : active<logger> {
  void init() { }; // required
  void destroy() { }; // required
  void operator() (string const & message) {
    active<logger>::post(bind(&logger::write, this, string(message)));
  }
  void write(string message) {
    cout << message << endl;
  }
};

// ...
vector<string> messages;
logger log_;
for_each(messages.begin(), messages.end(), ref(log_));

--->8--

Hope this helps!

-- 
Dean Michael C. Berris
Software Engineer, Friendster, Inc.

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk