Example
Example 22 shows how an asynchronous function call can be converted to a simple active object.
Example 22 – Encapsulating asynchronous operations in an active object
#include <rw/thread/RWTThreadIOUFunction.h>
#include <rw/itc/RWTIOUResult.h>
#include <rw/functor/rwBind.h>
 
using namespace std;
 
class AsyncService; // Forward reference for inlines!
 
class AsyncService {
private:
RWTThreadIOUFunction<int> thread_;
protected:
int syncService() // 1
{
int status = 0;
// Do something useful that produces a status
// value indicating success or failure
rwSleep(1000); // Waste some time...
return status;
}
 
public:
AsyncService() { // 2
thread_ = RWTThreadIOUFunction<int>::make(rwBind(
&AsyncService::syncService, this));
thread_.start();
}
~AsyncService() { // 3
thread_.join();
}
RWTIOUResult<int> operator()() const // 4
{
return thread_.result();
}
};
 
void
main()
{
cout << "Start the request" << endl;
AsyncService request; // 5
RWTIOUResult<int> iou = request(); // 6
cout << "Redeemed value of IOU: " << iou << endl; // 7
} // 8
//1 Defines the actual service that is to be executed in a separate thread.
//2 Defines a constructor that creates a thread to perform the operation.
//3 Defines a destructor that joins the thread.
//4 Includes an accessor for retrieving the IOU result of the operation.
//5 Constructs a named object to start the operation.
//6 Retrieves the future result of the operation as an IOU.
//7 Redeems the result, blocking (if necessary) until the operation has completed.
//8 Destroys the service object at end of scope, and automatically joins with the thread that was created.