Thursday, August 12, 2010

Active Object







Active Object a.k.a Actor is a great design pattern that should be used way more in my opinion. Instead of using raw threads you have them encapsuled in an object. This gives you easy concurrency and good handling of threads that avoids many of the pitfalls of using raw threads (races, etc). I've put together an example expired by Herb Sutter's article "Prefer using active objects instead of naked threads" but using generic callbacks since I do not have access to any C++0x yet 

Herb shows how you with C++0x can do this:

class Backgrounder {
public:
  // Save and Print will execute the lambdas in the 
  // background thread (active object thread)
  void Save(string filename){a.Send([=]{ … }); } 
  void Print(Data& data) {a.Send([=, &data] { … } ); }
private:
  Active a;
};
Mmm, nice way of utilizing lambda expressions, don't you think? However, with just plain old pre-C++0x (like most of us use in 2010) You can with normal C++ and a touch of template magic get this:

class Backgrounder {
public:
  void Save(string filename){
    a.send(bind(this, &Backgrounder::BgSave, filename));  }

  void Print( Data& data ){
    a.send(bind(this, &Backgrounder::BgPrint, data));
  }
private:
  void BgSave(string filename){...}
  void BgPrint(Data&; data){...}
  Active a;
};

Easy as 1, 2, 3 don't you think? And that's all it takes for working with an Active object that will execute jobs in the background. Why EVER use naked threads again for normal mundane tasks like bakground processing, saving files etc?

For more details and information how the Active works you can find my article here. It is heavily influenced by Herbs article and his Gotw 83 (Generic Callbacks :)


Till next time. Cheers
 Kjell 

4 comments:

Mark said...

You are using:
Active a;
Can you show definition of Active class ?

Thanks
Marek

KjellKod said...

Well... I suggest following the links that I mention.

dontevenbother said...

Could you also talk a little about the difference between the active object/actor , reactor , proactor (boost::asio) pattern , and what are the decisive factors in choosing one design pattern over another.

KjellKod said...

@dontevenbother.

My new blow is kjellkod.wordpress.com that is where I normally receive and respond to comments.

The difference between active object, reactor, proactor and when choosing one over the other is very interesting,.. out of the scope for my active object text though but it is a nice thought. I will keep it for the future.

Thank you for the input and you are welcome to kjellkod.wordpress.com