Я ожидал, что код ниже напечатать Привет, мир! каждые 5 секунд, но происходит то, что программа останавливается на 5 секунд, а затем печатает сообщение снова и снова без последующих пауз. Что мне не хватает?boost asio deadline_timer
#include <iostream>
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
using namespace boost::asio;
using namespace std;
io_service io;
void print(const boost::system::error_code& /*e*/)
{
cout << "Hello, world!\n";
deadline_timer t(io, boost::posix_time::seconds(5));
t.async_wait(print);
}
int main()
{
deadline_timer t(io, boost::posix_time::seconds(5));
t.async_wait(print);
io.run();
return 0;
}
Редактировать, чтобы добавить рабочий код ниже. Спасибо, парни.
#include <iostream>
#include <boost/bind.hpp>
#include <boost/thread.hpp>
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
using namespace boost::asio;
using namespace std;
class Deadline {
public:
Deadline(deadline_timer &timer) : t(timer) {
wait();
}
void timeout(const boost::system::error_code &e) {
if (e)
return;
cout << "tick" << endl;
wait();
}
void cancel() {
t.cancel();
}
private:
void wait() {
t.expires_from_now(boost::posix_time::seconds(5));
t.async_wait(boost::bind(&Deadline::timeout, this, boost::asio::placeholders::error));
}
deadline_timer &t;
};
class CancelDeadline {
public:
CancelDeadline(Deadline &d) :dl(d) { }
void operator()() {
string cancel;
cin >> cancel;
dl.cancel();
return;
}
private:
Deadline &dl;
};
int main()
{
io_service io;
deadline_timer t(io);
Deadline d(t);
CancelDeadline cd(d);
boost::thread thr1(cd);
io.run();
return 0;
}
, для чего 'ОтменаDeadline'? Я прокомментировал этот класс и 'CancelDeadline cd (d); boost :: thread thr1 (cd); 'и код все еще работает. – javapowered
Возможно, вас заинтересует этот вопрос: http://stackoverflow.com/questions/21771639/can-i-use-a-stackful-coroutine-as-the-wait-handler-of-a-steady-timer-which -is-de – updogliu