| Home | Libraries | People | FAQ | More

### Overview

One of the primary benefits of Boost.Fiber is the ability to use asynchronous operations for efficiency, while at the same time structuring the calling code as if the operations were synchronous. Asynchronous operations provide completion notification in a variety of ways, but most involve a callback function of some kind. This section discusses tactics for interfacing Boost.Fiber with an arbitrary async operation.

For purposes of illustration, consider the following hypothetical API:

    class AsyncAPI {
    public:
        // constructor acquires some resource that can be read and written
        AsyncAPI();

        // callbacks accept an int error code; 0 == success
        typedef int errorcode;

        // write callback only needs to indicate success or failure
        template< typename Fn >
        void init_write( std::string const& data, Fn && callback);

        // read callback needs to accept both errorcode and data
        template< typename Fn >
        void init_read( Fn && callback);

        // ... other operations ...
    };

The significant points about each of `init_write()` and `init_read()` are:

- The `AsyncAPI` method only initiates the operation. It returns immediately, while the requested operation is still pending.
- The method accepts a callback. When the operation completes, the callback is called with relevant parameters (error code, data if applicable).

We would like to wrap these asynchronous methods in functions that appear synchronous by blocking the calling fiber until the operation completes. This lets us use the wrapper function’s return value to deliver relevant data.

| Tip
`promise<>` and `future<>` are your friends here.