简体   繁体   English

它如何使用 boost.asio.deadline_timer 在单个线程中执行除“async_wait”之外的其他工作

[英]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".我重写了一个 boost.asio 示例“Timer.3 - 将 arguments 绑定到处理程序”。 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 why.我很难思考为什么。

If this can't work,how can I do other things except "async_wait" in one single thread.如果这不起作用,我怎么能在一个线程中做除了“async_wait”之外的其他事情。

#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.所以第一次调用print()时控制永远不会返回。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM