Threads Module User's Guide : PART II Concurrency Packages : Chapter 5 The Interthread Communication Package : The IOU Classes : Using IOUs
Using IOUs
Obtaining results from asynchronous operations often requires complex synchronization that is difficult to code and difficult to understand. The IOU object has an easy-to-use mechanism that simplifies this retrieval process.
Example
The following example demonstrates the use of an IOU object for retrieving the results of an operation executed in another thread. Example 45 uses a form of threaded runnable that invokes a function and stores any return value into an IOU.
Example 45 – Using an IOU object to retrieve results from another thread
#include <rw/thread/RWRunnableSelf.h>
#include <rw/thread/RWTThreadIOUFunction.h>
#include <rw/itc/RWTIOUResult.h>
#include <iostream>
 
using namespace std;
 
int sync_service()
{
int status = 0;
// Do something useful that produces a status
// value indicating success or failure
rwSleep(1000); // Waste some time...
return status;
}
RWTIOUResult<int> async_service()
{
RWTThreadIOUFunction<int> thread;
thread = RWTThreadIOUFunction<int>::make(sync_service); // 1
thread.start(); // 2
return thread.result(); // 3
}
void main()
{
cout << "Starting asynchronous service..." << endl;
RWTIOUResult<int> iou = async_service(); // 4
cout << "Redeemed value of IOU: " << iou << endl; // 5
}
//1 Creates a threaded runnable to execute the service.
//2 Starts the thread.
//3 Returns the IOU result for the service.
//4 Invokes the asynchronous service.
//5 Redeems the IOU.
Closing and Redeeming an IOU
In this example, the RWThreadIOUFunction class closes the IOU when the sync_service() function returns a result back to the runnable.
Threads attempting to redeem an IOU that has not been closed block until another thread writes a result or exception to that IOU object. If an IOU is closed with an exception, any attempt to redeem the IOU produces that exception.
For more information, see “Closing an IOU” and “Redeeming an IOU.”
Using Active Objects
The example in “Example” shows how an asynchronous operation can be created. Although the implementation seems straightforward, it has a potential problem—it does not have a way to join with the thread that has been created, so it has no way to insure that the thread has exited before any process eventually exits.
Using an active object solves the join problem. For more information, see “Using Threads To Build Active Objects.”