我使用Qt编程(C++),但是我的问题在编程(最可能)方面是通用的。
为了简化事情,功能 GetInput(字符串输入)不断扫描新的输入。
根据输入,程序退出或调用递归函数。
问题是,RecursiveFunc()函数阻塞GetInput()函数,因此无法获得更多输入(使其无法退出)。基本上,RecursiveFunc()函数会一遍又一遍地调用它自己,所以GetInput函数永远不会返回,从而无法获得更多输入。从函数调用递归函数而不阻塞父函数C++
我的问题:函数如何调用递归函数,但是仍然继续运行并返回递归正在运行。
//needs to constantly scan for input
void GetInput(string input)
{
if (input == "exit")
{
//terminate program
//this point is never reached after calling RecursiveFunc()
}
else if (input == "program1")
{
//Code executions gets stuck here because of recursion
RecursiveFunc();
int i = 0; //this statement is never reached, for example
}
}
void RecursiveFunc()
{
//update some values
//do some more things
//sleep a little, then call the fuction again
RecursiveFunc()
}
我想,类似的东西到发射后不管机制是必要的,但我不能完全弄清楚。我可以使用线程,但我试图避免这种情况(因为程序应尽可能简单)。如前所述,我正在使用Qt。
那么,我有什么选择?简单性最好的解决方案是什么?
你究竟想要达到什么目的? –
当递归深度变得足够长时,RecursiveFunc like发布会崩溃(至少未优化的,调试版本),堆栈溢出。 –