开发者

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

开发者 https://www.devze.com 2023-03-10 03:58 出处:网络
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

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

精彩评论

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

关注公众号