2017-07-23 19 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 
} 

我不知道這是否是一個很好的做法,但它適用於現在。