Skip to content

Instantly share code, notes, and snippets.

@jamboree
Created January 17, 2015 13:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamboree/3b8716ad1922749e77ae to your computer and use it in GitHub Desktop.
Save jamboree/3b8716ad1922749e77ae to your computer and use it in GitHub Desktop.
#include <cstdlib>
#include <iostream>
#include <future>
#include <experimental/resumable>
#include <boost/thread/future.hpp>
namespace boost {
template <class T>
bool await_ready(future<T> & t)
{
return t.is_ready();
}
template <class T, class Promise>
void await_suspend(
future<T> & t, std::experimental::resumable_handle<Promise> rh)
{
t.then([=](auto&& result) mutable {
if (result.has_exception())
rh.promise().set_exception(result.get_exception_ptr());
rh();
});
}
template <class T>
auto await_resume(future<T> & t)
{
return t.get();
}
}
namespace std {
namespace experimental {
template <typename T, typename... anything>
struct resumable_traits<boost::future<T>, anything...> {
struct promise_type {
boost::promise<T> promise;
bool cancelling = false;
auto get_return_object() { return promise.get_future(); }
suspend_never initial_suspend() { return{}; }
suspend_never final_suspend() { return{}; }
template <class U = T, class = enable_if_t< is_void<U>::value >>
void set_result() {
promise.set_value();
}
template < class U, class U2 = T,
class = enable_if_t < !is_void<U2>::value >>
void set_result(U&& value) {
promise.set_result(std::forward<U>(value));
}
void set_exception(std::exception_ptr e) {
try
{
std::rethrow_exception(e);
}
catch (...)
{
promise.set_exception(boost::current_exception());
cancelling = true;
}
}
void set_exception(boost::exception_ptr e) {
promise.set_exception(std::move(e));
cancelling = true;
}
bool cancellation_requested()
{
return cancelling;
}
};
};
}
}
template<class Promise>
boost::future<void> test(Promise& p)
{
auto f = p.get_future();
std::cout << "start----------------\n";
std::cout << "got: " << __await f << "\n";
std::cout << "end----------------\n";
}
int main(int argc, char *argv[])
{
std::promise<int> p; // ok
//boost::promise<int> p; // hang
auto f = test(p);
p.set_value(5);
f.wait();
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment