Skip to content

Instantly share code, notes, and snippets.

@jbandela
Last active December 20, 2015 06:49
Show Gist options
  • Save jbandela/6089137 to your computer and use it in GitHub Desktop.
Save jbandela/6089137 to your computer and use it in GitHub Desktop.
#include <future>
#include <iostream>
#include <type_traits>
using namespace std;
// Adapted from http://stackoverflow.com/questions/14200678/c11-async-continuations-or-attempt-at-then-semantics
namespace detail{
template<typename F, typename W, typename R>
struct helper
{
F f_;
W w_;
helper(F f, W w)
: f_(f)
, w_(w)
{
}
helper(const helper& other)
: f_(other.f_)
, w_(other.w_)
{
}
helper(helper && other)
: f_(std::move(other.f_))
, w_(std::move(other.w_))
{
}
helper& operator=(helper other)
{
f_ = std::move(other.f_);
w_ = std::move(other.w_);
return *this;
}
R operator()()
{
cerr << "In operator()\n";
f_.wait();
return w_(f_);
}
};
}
template<typename F, typename W>
auto then(F f, W w) -> std::shared_future<decltype(w(f))>
{
std::shared_future < decltype(w(f))> ret = std::async(std::launch::async, detail::helper<F, W, decltype(w(f))>(f, w));
return ret;
}
void test_then()
{
std::shared_future<int> result = std::async([]{ return 12; });
auto w = [](std::shared_future<int> rf) {
auto r = rf.get();
cout << "[after] thread id = " << std::this_thread::get_id() << endl;
cout << "r = " << r << endl;
return r*r;
};
auto f = then(result, w);
auto f2 = f;
cout << "Final result f = " << f.get() << endl;
cout << "Final result f2 = " << f2.get() << endl;
}
int main(){
test_then();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment