Skip to content

Instantly share code, notes, and snippets.

@nekko1119
Created April 7, 2016 09:40
Show Gist options
  • Save nekko1119/0defd1fe16a78654bb0b7f400e8264f6 to your computer and use it in GitHub Desktop.
Save nekko1119/0defd1fe16a78654bb0b7f400e8264f6 to your computer and use it in GitHub Desktop.
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <functional>
#include <iostream>
#include <thread>
class printer
{
boost::asio::deadline_timer timer1;
boost::asio::deadline_timer timer2;
boost::asio::io_service::strand strand;
int count;
public:
explicit printer(boost::asio::io_service& io)
: timer1{io, boost::posix_time::seconds{1}},
timer2{io, boost::posix_time::seconds{1}},
strand{io},
count{0}
{
this->timer1.async_wait(this->strand.wrap(std::bind(&printer::print1, this)));
this->timer2.async_wait(this->strand.wrap(std::bind(&printer::print2, this)));
}
~printer() noexcept
{
std::cout << "final count is " << this->count << std::endl;
}
void print1()
{
if (this->count >= 10) {
return;
}
std::cout << "timer1 " << this->count << std::endl;
++this->count;
this->timer1.expires_at(this->timer1.expires_at() + boost::posix_time::seconds{1});
this->timer1.async_wait(this->strand.wrap(std::bind(&printer::print1, this)));
}
void print2()
{
if (this->count >= 10) {
return;
}
std::cout << "timer2 " << this->count << std::endl;
++this->count;
this->timer2.expires_at(this->timer2.expires_at() + boost::posix_time::seconds{1});
this->timer2.async_wait(this->strand.wrap(std::bind(&printer::print2, this)));
}
};
int main()
{
boost::asio::io_service io;
printer p{io};
std::thread thread{[&io]() { io.run(); }};
io.poll();
std::cout << "hoge" << std::endl;
thread.join();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment