|
Boost : |
From: Thorsten Schuett (schuett_at_[hidden])
Date: 2005-08-16 04:07:52
Hi,
Hartmut and I wrote a small library which implements futures for C++. I
uploaded the code to the boost-sandbox vault. If you find anything odd in
there (like e.g. overloading operator T()), you have to blame me, if you find
interesting stuff in there, you have to blame Hartmut.
The most basic future is simple_future<T>. Its constructor takes a function
which returns T and spawns a new thread executing this function. Afterwards
you can call operator()() to block until the thread is done and get the
result.
int slow_fac(int n){
if(n == 0)
return 0;
if(n == 1)
return 1;
sleep(1);
return n * fac(n - 1);
}
simple_future<int> f1 = bind(slow_fac, 4);
...
cout << f1() << endl; //should print 24
if you have two different implementations of fac and you are only interested
in the result of the faster implementation, you can combine two futures using
'||'.
int fast_fac(int n){
if(n == 0)
return 0;
if(n == 1)
return 1;
return n * fac(n - 1);
}
simple_future<int> f2 = bind(fast_fac, 4);
future<int> f3 = f1 || f2;
...
cout << f3() << endl; // should print 24
If the result type of the futures given to '||' differ, the result type of the
new future is a variant over the types.
double fac4(){
return (double)fast_fac(4);
}
future<variant<int, double> > f4 = f2 || double_[&fac4];
//double_[] creates a simple_future<double>
Similarly, the '&&'-operator creates a tuple of the types of the individual
futures and blocks until all futures are done.
future<tuple<int, double> > f5 = f2 && double_[&fac4];
Warning:
I overloaded operator T() for futures to get a nicer syntax.
int fac_of_4 = f1; // <- this works!
Thorsten
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk