Boost C++ Libraries

...one of the most highly regarded and expertly designed C++ library projects in the world. Herb Sutter and Andrei Alexandrescu, C++ Coding Standards

PrevUpHomeNext

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:

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] Tip

promise<> and future<> are your friends here.


PrevUpHomeNext