I rewrite a boost.asio example "Timer.3 - Binding arguments to a handler". I think "worker" can work forever and "print" can be called each second. But "print" only is called once. It is very diffcult for me to think 开发者_JAVA百科why.
If this can't work,how can I do other things except "async_wait" in one single thread.
#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
int num = 0;
void worker(){
while(1){
++num;
}
}
void print(const boost::system::error_code& /*e*/,
boost::asio::deadline_timer* t, int* count)
{
std::cout << *count << "\n";
++(*count);
t->expires_at(t->expires_at() + boost::posix_time::seconds(1));
t->async_wait(boost::bind(
print, boost::asio::placeholders::error, t, count
));
if(*count == 1){
worker();
}
}
int main()
{
boost::asio::io_service io;
int count = 0;
boost::asio::deadline_timer t(io, boost::posix_time::seconds(1));
t.async_wait(boost::bind(print,
boost::asio::placeholders::error, &t, &count
));
io.run();
std::cout << "Final count is " << count << "\n";
return 0;
}
You have an infinite loop
void worker() {
while(1) {
++num;
}
}
so control never returns the first time print()
is invoked.
精彩评论