Does "C ++ boost :: asio Recursive timer callback" accumulate callstack?
I want to make a C ++ program so that one thread will periodically send a network message at 1 second intervals.
I've heard about how to boost the library of the most useful cross platform library for C ++ support.
My first idea is below.
- Define one function that has logic to send an N / W¹ message.
- Write timer binding with above function.
- 1. The function has logic that registers itself (same with 2.) at the end of the block.
- Then, while this thread is running, the send N / W message logic¹ is recursively called every 1 second.
The main test is complete success. But is it possible that this way would make an endless challenge? (e.g. timer_steadyTimerReculsive () -> print2 () -> print2 () -> print2 () -> print2 () -> print2 () ...)
I know in theory that the stop call is accumulating in the cpu register. So sometimes a fatal error occurs in NodeJS due to unused infinite call from infinite callbacks.
If this way makes an endless call, how can I solve this problem for this program purpose?
Or, it might be helpful to tell me how I can debug this asynchronous callback method in Visual Studio.
I tried to run debug mode in Visual Studio. But VS cannot follow / catch the callstack of the callback method after binding the handler to the 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 private company).
source to share
No, async_ * methods always return immediately after the work is published to the service for asynchronous execution.
In fact, if you don't call io_service::{run|poll}[_one]()
, nothing is done.
You don't need to worry about stack overflow if you are not inserting recursive calls synchronously. With asynchronous calls, you don't actually get nesting.
source to share