执行"C ++ boost :: asio递归计时器回调"积累调用栈? [英] Do "C++ boost::asio Recursive timer callback" accumulate callstack?
问题描述
我想让C ++程序使一个线程以1秒的间隔定期发送网络消息.
I want to make C++ program that one thread sends the network message periodically at 1 seconds interval.
我听说了boost库,它是支持c ++的最有用的跨平台库.
I heard about boost library the most useful cross-platform library to support c++.
下面是我的第一个想法.
My first idea is below.
- 定义一个具有发送N/W消息逻辑的功能.
- 注册计时器与上述功能绑定.
- 1.Function具有在块的末尾注册自身(与2相同)的逻辑.
- 然后,在此线程运行时,每1秒递归调用一次发送N/W消息¹逻辑.
基本测试是完全成功的. 但是,我不知道这种方式是否可能导致无限调用堆栈?(例如,timer_steadyTimerReculsive()-> print2()-> print2()-> print2()-> print2()-> print2()...)
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() ...)
从理论上讲,我知道调用堆栈是在cpu寄存器上累积的.因此,有时由于无限回调中未执行的无限调用堆栈,导致NodeJS中出现致命错误.
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.
如果通过这种方式产生无限调用堆栈,我该如何解决此程序目标的问题?
或者,很高兴告诉我如何在Visual Studio中调试此异步回调方法.
我试图在Visual Studio中运行调试模式.但是,在处理程序绑定到io_service之后,VS无法跟随/捕获回调方法的调用堆栈.
I tried to run debug mode in Visual Studio. But VS cannot follow/catch the callback method callstack after handler binding to io_service.
我的代码如下.
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消息逻辑是公司私有的东西.)
¹ (N/W message logic is company-private thing.)
推荐答案
不,在将工作发布到服务以进行异步执行之后,async_ *方法总是立即返回.
No, async_* methods always immediately return, after posting the work to the service for asynchronous execution.
实际上,如果您不拨打io_service::{run|poll}[_one]()
,将一事无成.
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.
这篇关于执行"C ++ boost :: asio递归计时器回调"积累调用栈?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!