简体   繁体   English

我的代码是否等同于Boost.Asio教程中给出的代码?

[英]Is my code equivalent to the one given in the Boost.Asio tutorial?

I'm learning Boost.Asio and this is the code I'm talking about: Link to code 我正在学习Boost.Asio,这是我正在谈论的代码: 链接到代码

The following code I have written appears to be the same and it works: (compile with "-lboost_system" and "-std=c++11") 我编写的以下代码似乎相同并且可以正常工作:(使用“ -lboost_system”和“ -std = c ++ 11”编译)

#include<iostream>
#include<boost/asio.hpp>
#include<functional>
#include<boost/date_time/posix_time/posix_time.hpp>

typedef const boost::system::error_code cbse;
int main()
{
    boost::asio::io_service io;

    boost::asio::deadline_timer t(io,boost::posix_time::seconds(1));

    int count=0;

    std::function<void(cbse&)> 
    cb=[&](cbse&)
    {
        if(count<5)
        {
            std::cout<<"foo"<<std::endl;
            count++;
            t.expires_at(t.expires_at()+boost::posix_time::seconds(1));
            t.async_wait(cb);
        }
        else
            std::cout<<"done"<<std::endl;
    };

    t.async_wait(cb);

    std::cout<<"Hello"<<std::endl;

    io.run();

    return 0;
}

Am I missing some important distinction? 我是否缺少一些重要的区别?
Also recursively calling the callback does not seem like a good idea to me intuitively, is it given in the doc just for the sake of explanation? 同样递归地调用回调在我看来似乎不是一个好主意,是在文档中给出它仅仅是为了说明吗?

Am I missing some important distinction? 我是否缺少一些重要的区别?

Your code looks ok, and has about the same behavior as the example code you linked to. 您的代码看起来还不错,并且行为与您链接到的示例代码大致相同。 The only real difference is that you're accessing t and count from the enclosing scope, rather than using parameters. 唯一真正的区别是您要从封闭的范围访问tcount ,而不是使用参数。 This is ok in a simple example like this, but can introduce problems for more complex code. 在这样的简单示例中可以这样做,但可能会给更复杂的代码带来问题。

Also recursively calling the callback does not seem like a good idea to me intuitively, is it given in the doc just for the sake of explanation? 同样递归地调用回调在我看来似乎不是一个好主意,是在文档中给出它仅仅是为了说明吗?

Calling async_wait again from the callback is essential to get the desired behavior. 从回调中再次调用async_wait对于获得所需的行为至关重要。 Otherwise the callback would be called only once. 否则,回调将仅被调用一次。

Chaining asynchronous callbacks like this can be very useful when done with care, but can quickly lead to difficult to understand/debug code if not. 像这样链接异步回调可能非常有用,但是如果不这样做的话,很快会导致难以理解/调试代码。

Your code seems to be ok. 您的代码似乎没问题。

What you do is not recursively calling, because deadlock_timer::async_wait just posts an event and returns immediately. 您所做的不是递归调用,因为deadlock_timer::async_wait只是发布一个事件并立即返回。 The callback is actually called from loop in ioservice::run . 回调实际上是从ioservice::run循环调用的。

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

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