Calling the recursive function from the function without blocking parent C ++ function

advertisements

This question already has an answer here:

  • How can I run 3 QProcess in background using the same executable 1 answer

I'm programming with Qt (c++) but my issue is universal in programming (most probably).
To simplify things, the function GetInput(string input) continuously scans for new input.
Depending on the input, the program exits or calls a recursive function.

The problem is, the RecursiveFunc() function blocks the GetInput() function, thus making it impossible to get further input (making it impossible to exit). Basically, the RecursiveFunc() function will call itself over and over, so the GetInput function never returns, making it impossible to get any more input.

My Question: How does a function call a recursive function BUT STILL continuously run and return WHILE the recursion is running.

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

I'm thinking, something similiar to a fire-and-forget mechanism would be needed, but I can't quite figure it out. I could probably use threads, but I'm trying to avoid that (as the program should stay as simple as possible). As stated, I'm using Qt.

So, what options do I have? What's the best solution in terms of simplicity?


Threads, co-routines, message loops with timers.

Qt has a message loop; change architecture to use that is simplest.

Co-routines lack language support, but there are myriads of implementations people have hacked together.

Threading is complex to get right, but keeps each code looking mostly linear.

Conclusion: Rewrite your code to be message loop based. Instead of recursive and sleeping, post a delayed message to do work later.