开发者

how can it do other work except "async_wait" in one single thread using boost.asio.deadline_timer

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜