Skip to content

Instantly share code, notes, and snippets.

@chenfengyuan
Created January 15, 2015 06:44
Show Gist options
  • Save chenfengyuan/4d764b0bca82a42c05a9 to your computer and use it in GitHub Desktop.
Save chenfengyuan/4d764b0bca82a42c05a9 to your computer and use it in GitHub Desktop.
boost use callback functions in stackfull coroutine
#include <iostream>
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/asio/spawn.hpp>
#include <memory>
void bar(boost::asio::io_service &io, std::function<void()> cb){
auto ptr = std::make_shared<boost::asio::deadline_timer>(io, boost::posix_time::seconds(1));
ptr->async_wait([ptr, cb](const boost::system::error_code&){cb();});
}
template<typename Handler>
void foo(boost::asio::io_service &io, Handler && handler){
typename boost::asio::handler_type<Handler, void()>::type handler_(std::forward<Handler>(handler));
boost::asio::async_result<decltype(handler_)> result(handler_);
bar(io, handler_);
result.get();
return;
}
int main()
{
boost::asio::io_service io;
boost::asio::spawn(io, [&io](boost::asio::yield_context yield){
foo(io, yield);
std::cout << "hello, world!\n";
});
io.run();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment