The Active Object design pattern decouples method execution from method invocation that reside in their own thread of control. The goal is to introduce concurrency, by using asynchronous method invocation and a scheduler for handling requests. I.e in short you encapsulate a private thread inside your object and by feeding it with work that are processed in the background your object gets an asynchronous “dimension”. This makes it much easier to make threaded software compared to doing it with “raw” threads.
When Herb Sutter wrote about Active Objects in this Effective Concurrency blog series [blog entry: Prefer Using Active Objects Instead of Naked Threads] I was thrilled since I was waiting for that since his Effective Concurrency seminar in Kista, Stockholm back in 2009.
Herb explained a simple to follow cookbook for getting your Active Object right. Either with standard C++ using an object oriented approach for passing message objects to the thread queue or by using C++0x with lambda support and std::thread and other niceties.
Since I thought the “object oriented” approach was clumsy and would lead to lots of boilerplate code I worked on a more clean approach that would to use the features similar to C++0x but using template magic for (Gotw83) generic callbacks and normal standard C++ (witout using std::tr1). I showed this in my old blog with standard c++ code that can be downloaded from kjellkod.cc/active_object.
However, just recently I made a job move from HiQ to Prevas and with that came a week or so between assignments. This gave me a great opportunity to learn more of the new C++0x with the help of just::thread implementation of the new C++0x standard library. The result was much cleaner, more readable code with guaranteed cross-platform behavior using std::thread with a std::mutex protected message queue for thread communication. This is a huge improvement over the sketchy “lock-free circular fifo” I used in my first Active Object example.
For the new and improved Active Object I used standard library components and with the just::thread portability bundle I soon had a cross platform Active Object that works like a charm on both Windows (Visual Studio 2010 Express) and Linux Ubuntu (g++) .
Using Git you can download the latest snapshot of my Active Object example at git://github.com/KjellKod/KjellKod.git or you can get it from http://www.kjellkod.cc/active-object-with-cpp0x where I explain the details of it.