我正在使用Qt(c ++)进行编程,但我的问题在编程方面很普遍(最有可能)
为简化起见,函数 GetInput(字符串输入)不断扫描新输入。
根据输入,程序退出或调用递归函数
问题是,RecursiveFunc()函数阻止了GetInput()函数,因此无法获得进一步的输入(使其无法退出)。基本上, RecursiveFunc()函数会反复调用自身,因此GetInput函数永远不会返回,从而无法再获得任何输入。
我的问题:函数如何调用递归函数但是STILL继续运行并返回WHILE递归正在运行。
//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。
那么,我有什么选择?在简单性方面,最佳解决方案是什么?
答案 0 :(得分:3)
线程,协同例程,带定时器的消息循环。
Qt有一个消息循环;改变使用最简单的架构。
协同惯例缺乏语言支持,但是有无数的实施人员一起入侵。
线程很复杂,但要保持每个代码看起来都是线性的。
结论:重写您的代码,使其成为基于消息循环的代码。而不是递归和睡眠,发布延迟的消息以便稍后工作。
答案 1 :(得分:-2)
好的,
我找到了一种方法来实现我想要的,没有任何花哨的消息循环,也没有重写我的整个代码。我不是递归地调用RecursiveFunc(),而是递归地调用GetInput()(使用qobject元调用)。
简化,这是我的黑客解决方案:
//needs to constantly scan for input
void GetInput(string input)
{
if (input == "x")
{
//terminate program
}
else if (input == "program1")
{
RecursiveFunc();
//sleep a little
GetInput(""); //calls GetInput() recursively
}
}
void RecursiveFunc()
{
//update some values
//do some more things
}
我不确定这是否是一个非常好的做法,但它现在有效。