2017-07-23 23 views
-1

我使用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。

那么,我有什么选择?简单性最好的解决方案是什么?

+2

你究竟想要达到什么目的? –

+1

当递归深度变得足够长时,RecursiveFunc like发布会崩溃(至少未优化的,调试版本),堆栈溢出。 –

回答

3

线程,协程,带定时器的消息循环。

Qt有一个消息循环;改变架构使用最简单。

联合程序缺乏语言支持,但是有大量的实现人们被黑客攻击。

线程是很复杂的得到正确的,但保持每个代码大多线性。

结论:将您的代码重写为基于消息循环。而不是递归和睡眠,发布延迟的消息以后再做工作。

-2

好吧,

我找到了一种方法来达到我想要的东西,没有任何花哨的消息循环,并无需重写我的整个代码。递归调用RecursiveFunc(),而不是递归地调用GetInput()(使用qobject元调用)。

简化,这是我的hackerishy解决方案:

//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 
} 

我不知道这是否是一个很好的做法,但它适用于现在。