Active object pattern

Active object pattern wraps an asynchronous operation in an object containing a worker thread and a request input queue. Thus it can be seen as another name for the actor pattern. A known example is the wrapping of asynchronous writes to a log file with an active object to offload logging to a background thread as in the following example:

class AsyncLogFile
{
public:
void write(const QString& str)
{
// we use a lambda taking a copy of the data with it
a_.send( [=] { log_.write(str); } );
}
private:
SyncLogFile log_; // log file
ActiveObject a_; // helper (queue+thread)
};

AsyncLogFile logFile;
logFile.write(" text text text ... ");

A drawback of this technique is that we waste one whole thread for a single type of task, but for I/O operations this can be justifiable because that thread would be mostly sleeping. Also, note that sending a lambda through std::function incurs a cost of one memory allocation (type erasure used in std::function)—this is the cost of a general implementation in this case.