Do “C++ boost::asio Recursive timer callback” accumulate callstack?

时光毁灭记忆、已成空白 提交于 2020-01-05 05:40:26

问题


I want to make C++ program that one thread sends the network message periodically at 1 seconds interval.

I heard about boost library the most useful cross-platform library to support c++.

My first idea is below.

  1. Define one function which has the logic to send N/W message¹.
  2. Register timer bind with above function.
  3. 1.Function has logic which register itself(same with 2.) at end of the block.
  4. Then, while this thread is running, the send N/W message¹ logic is recursively called every 1 seconds later.

The basic test is completely success. But, I wonder it is possible that this way make infinite-callstack? (eg. timer_steadyTimerReculsive()->print2()->print2()->print2()->print2()->print2() ...)

I theoretically know that callstack is accumulated on cpu register. So sometimes there is fatal error in NodeJS because of unexepceted infinite-callstack from infinite-callbacks.

If this way makes infinite-callstack, how can I solve this problem for this program goal?

Or, It will be appreciate to tell me how can I debug this asynchronous callback method in Visual Studio.

I tried to run debug mode in Visual Studio. But VS cannot follow/catch the callback method callstack after handler binding to io_service.

My code is below.

    void print2(const boost::system::error_code& e, boost::asio::steady_timer* timer, int* count) {
        /* N/W message sending logic here*/
        (*count)++;
        timer->expires_from_now(chrono::seconds(1));
        timer->async_wait(boost::bind(print2, boost::asio::placeholders::error, timer, count));

    }
    void timer_steadyTimerReculsive() {

        boost::asio::io_service io;
        int count = 0;
        boost::asio::steady_timer timer(io);
        timer.async_wait(boost::bind(print2, boost::asio::placeholders::error, &timer, &count));

        io.run();
    }
    int main() {
        timer_steadyTimerReculsive();

        cout << "end method" << endl;
        return 0;
    }

¹ (N/W message logic is company-private thing.)


回答1:


No, async_* methods always immediately return, after posting the work to the service for asynchronous execution.

In fact, if you don't call io_service::{run|poll}[_one]() nothing ever gets done.

You don't need to worry about stack overflow unless you synchronously nest recursive calls. With the asynchronous calls you don't actually get nesting.



来源:https://stackoverflow.com/questions/43495221/do-c-boostasio-recursive-timer-callback-accumulate-callstack

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!