Skip to content

Instantly share code, notes, and snippets.

@JohnCoconut
Last active January 21, 2019 14:52
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 JohnCoconut/ff64371a6e82930ee2f355a7a9e96965 to your computer and use it in GitHub Desktop.
Save JohnCoconut/ff64371a6e82930ee2f355a7a9e96965 to your computer and use it in GitHub Desktop.
Async wait from asio steady timer
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <iostream>
namespace asio = boost::asio;
void bind_handler(const boost::system::error_code& ec, asio::steady_timer& t, int count, int instance_tag)
{
if (!ec) {
if (count > 0) {
std::cout << "instance " << instance_tag << " getting " << count << "\n";
auto num_of_canceled = t.expires_at(t.expiry() + std::chrono::seconds(1));
if (num_of_canceled) {
std::cout << "instance " << instance_tag << " canceled "
<< num_of_canceled << " await operations\n";
}
t.async_wait(boost::bind(bind_handler,
asio::placeholders::error, boost::ref(t), --count, instance_tag));
}
}
else if (ec == asio::error::operation_aborted) {
std::cout << ec.message() << std::endl;
}
else
std::cout << "You shouldn't see this line\n";
std::cout << "-------------done-------------------\n";
}
int main()
{
asio::io_context io_context(1);
asio::steady_timer t(io_context, std::chrono::seconds(1));
int count = 20;
int instance_1 = 1;
int instance_2 = 2;
t.async_wait(boost::bind(bind_handler, asio::placeholders::error, boost::ref(t), count, instance_1));
t.async_wait(boost::bind(bind_handler, asio::placeholders::error, boost::ref(t), count, instance_2));
io_context.run();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment