Last active
January 21, 2019 14:52
-
-
Save JohnCoconut/ff64371a6e82930ee2f355a7a9e96965 to your computer and use it in GitHub Desktop.
Async wait from asio steady timer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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