async allows you to call any C++ function or functor asynchronously. You are given a future object which may be queried for the return value or exception generated by the function.
> hg clone http://bitbucket.org/edd/async
Or get a zip file of the code.
Suppose we have a long-running function which counts the number of primes up to the given limit. For large values of
std::size_t count_primes_upto(std::size_t max);
This function may take a long time. We can use async to do useful work while this calculation is performed:
#include <async/call.hpp> async::layered_cage<async::catch_all> invoker; // this is an object that handles exceptions // call count_primes_upto(987654321) asynchronously async::future<std::size_t> fut = async::call(invoker, count_primes_upto, 987654321); // do something else in the mean time // ... std::size_t n = fut.value();
async supports the passing of arguments and receipt of return values by-reference using
using async::ref; // Load plugins in to the given vector and return a reference to the default const plugin &load_plugins(const std::string &location, const std::vector<plugin> &plugins); async::future<const plugin &> fut = async::call(invoker, ref(load_plugins), "plugins", ref(plugins));
I made a series of blog posts on the implementation details. Their a little out of date by now, but still generally relevant:
- An asynchronous function call mechanism: handling exceptions
- An asynchronous function call mechanism: futures
- An asynchronous function call mechanism: the final piece
All original content copyright© Edd Dawson.
Any opinions expressed by Edd are his own and are not necessarily shared by his employer. Or by anyone else, in fact.
All source code appearing on this website that was written by Edd Dawson is made available under the terms of the Boost software license version 1.0 unless otherwise stated or implied by the license associated with the work from which the code is derived.