Skip to content

Instantly share code, notes, and snippets.

@dirvine
Created December 11, 2014 14:44
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 dirvine/6e13a65ec814f322688f to your computer and use it in GitHub Desktop.
Save dirvine/6e13a65ec814f322688f to your computer and use it in GitHub Desktop.
aync_result example
#include "maidsafe/common/test.h"
#include <iostream>
#include "asio/io_service.hpp"
#include "asio.hpp"
// Note: the handler signatures here must contain
// boost::system::error_code as first argument (not std::error_code)
// for asio to understand it is to indicate errors.
template <typename CompletionToken>
typename asio::async_result<
typename asio::handler_type<CompletionToken, void(std::error_code, std::string)>::type>::type
my_fancy_async_operation(asio::io_service& ios, const std::string& message,
CompletionToken&& token) {
using handler_type =
typename asio::handler_type<CompletionToken, void(std::error_code, std::string)>::type;
handler_type handler(std::forward<decltype(token)>(token));
// The result must be defined here, otherwise we'll get segmentation
// fault when using coroutines (don't understand why though).
asio::async_result<handler_type> result(handler);
ios.post([handler, message]() mutable { handler(std::error_code(), message); });
return result.get();
}
// Link flags: -lboost_coroutine // If using coroutines
// -lboost_context // If using coroutines
// -lboost_system // For asio
// -lpthread // If using futures
#define USE_CALLBACKS 1
#define USE_FUTURES 1
#define USE_COROUTINES 1
#if USE_FUTURES
#include <thread>
#include "asio/use_future.hpp"
#endif
#if USE_COROUTINES
#include "asio/spawn.hpp"
#endif
int main(int argc, char** argv) {
asio::io_service ios;
#if USE_CALLBACKS
{
my_fancy_async_operation(ios, "handler", [](std::error_code, const std::string& msg) {
std::cout << "hello " << msg << std::endl;
});
ios.run();
}
#endif
#if USE_FUTURES
ios.reset();
{
asio::io_service::work work(ios);
std::thread io_thread([&ios]() { ios.run(); });
try {
auto msg = my_fancy_async_operation(ios, "future", asio::use_future).get();
std::cout << "hello " << msg << std::endl;
} catch (std::system_error error) {
// ...
}
ios.stop();
io_thread.join();
}
#endif
#if USE_COROUTINES
ios.reset();
{
asio::spawn(ios, [&ios](asio::yield_context yield) {
std::error_code error;
auto msg = my_fancy_async_operation(ios, "coroutine", yield[error]);
std::cout << "hello " << msg << std::endl;
});
ios.run();
}
#endif
return maidsafe::test::ExecuteMain(argc, argv);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment