问题
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.
- Define one function which has the logic to send N/W message¹.
- Register timer bind with above function.
- 1.Function has logic which register itself(same with 2.) at end of the block.
- 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