w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Escape from Recursion with a Time Limit

Given that recursion is to be used in a strictly timed environment, there are several options that can be considered. These are listed below:

OPTION 1:

    Add more if statements throughout the method body especially before segments of code that can block to ensure the code execution gets halted as soon as the time expires. A specific cushion interval must be implemented to give time for the return statements to propagate back up the stack.

Pros:

  • Simple to implement.
  • Relatively simple and effective.

Cons:

  • Degrades readability of code.
  • Does not guarantee execution will fall under specified time.


OPTION 2:

    Port the executive code to a secondary thread which progressively writes to an object as it executes. The primary thread can then start a timer while firing off this thread. When the timer expires the primary thread need only retrieve this object and inform the worker thread to die.

Pros:

  • Extremely accurate (results retrieved nearly on the dot with delays due to synchronization)
  • Does not need a cushion interval - The recursive function can go as deep as it wants without being tied back by trying to fit the return propagation within the timer.
  • Allows graceful shutdown of the executive code as it is no longer bounded by time (results are taken and the thread is allowed to die at its own pace).

Cons:

  • Multi-threaded - Due to this solution being multi-threaded, it may not be applicable to every scenario.
  • Requires a lot of extra code and possibly changes in some existing code to implement.




© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.