除了“async_wait”之外它怎么能做其他工作?在一个线程中使用 boost.asio.deadline_timer

发布于 2024-11-11 13:30:33 字数 1116 浏览 4 评论 0原文

我重写了 boost.asio 示例“Timer.3 - 将参数绑定到处理程序”。我认为“工人”可以永远工作,“打印”可以每秒调用。但“打印”只被调用一次。我很难思考为什么。

如果这不起作用,我该如何在一个线程中做除“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;
}

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 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;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

久而酒知 2024-11-18 13:30:33

您有一个无限循环

void worker() {
    while(1) {
        ++num;
    }
}

,因此第一次调用 print() 时控件永远不会返回。

You have an infinite loop

void worker() {
    while(1) {
        ++num;
    }
}

so control never returns the first time print() is invoked.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文