-1

So I have a Python code running with one very expensive function that gets executed at times on demand, but it's result is not needed straight away (it can be delayed by a few cycles).

def heavy_function(arguments):
    return calc_obtained_from_arguments

def main():
    a = None
    if some_condition:
        a = heavy_function(x)
    else:
        do_something_with(a)

The thing is that whenever I calculate the heavy_function, the rest of the program hangs. However, I need it to run with empty a value, or better make it know that a is being processed separately and thus should not be accessed. How can I move the heavy_function to separate process and keep calling the main function all the time until heavy_function is done executing, then read the obtained a value and use it in main function?

  • Possible duplicate of [Creating Threads in python](https://stackoverflow.com/questions/2905965/creating-threads-in-python) – stovfl Oct 28 '18 at 19:10

1 Answers1

0

You could use a simple queue.

  1. Put your heavy_function inside a separate process that idles as long as there is no input in the input queue. Use Queue.get(block=True) to do so. Put the result of the computation in another queue.
  2. Run your normal process with the empty a-value and check emptiness of the output queue from time to time. Maybe use while Queue.empty(): here.
  3. If an item becomes available, because your heavy_functionhas finished, switch to a calculation with the value a from your output queue.
RaJa
  • 1,471
  • 13
  • 17