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