0

I am currently writing a program that is required to be as fast as possible.

Currently, one of the functions looks like this:

def function():
    value = get_value()
    # Multiple lines of code

    if value == "1":
        print("success")

I want to know, if there is a way of calling the get_value() function at the start of the function and instantly running the multiple lines of code and then whenever the the get_value() function is finishes and returns a value the value variable is updated ready for the if statement.

Thanks!

wtreston
  • 1,051
  • 12
  • 28
  • [This post](https://stackoverflow.com/questions/6893968/how-to-get-the-return-value-from-a-thread-in-python) may answer your question. – Zehanort Aug 16 '19 at 14:26
  • what if `value` is returned in the middle of executing those "multiple lines of code" ? You need to clarify the control flow – RomanPerekhrest Aug 16 '19 at 14:28

1 Answers1

0

This is what futures are for. With the concurrent.futures module, you'd do something like:

import concurrent.futures

# Properly, this would be created once, in a main method, using a with statement
# Use ProcessPoolExecutor instead if the functions involved are CPU bound, rather
# than I/O bound, to work around the GIL
executor = concurrent.futures.ThreadPoolExecutor()

def function():
    value = executor.submit(get_value)

    # Multiple lines of code

    if value.result() == "1":
        print("success")

This creates a pool of workers that you can submit tasks to, receiving futures, which can be waited for when you actually need the result. I'd recommend looking at the examples in the documentation for more full-featured usage.

The other approach here, for largely I/O bound cases based on sockets, subprocesses, etc., is using asyncio with async/await, but that requires a complete rewrite of your code, and is out of scope for a short answer.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
  • Hi! Thanks for your answer! Quick question though. Lets say that the "Multiple Lines of Code" are done before the ```get_value()``` function is, will it wait for the result or cause the program to crash? Thanks! – wtreston Aug 16 '19 at 15:03
  • @wtreston: [The docs cover this already](https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Future.result); `Future.result()` will block if the future hasn't finished; by default it will wait forever, but you can pass a `timeout` argument to make it raise an exception if the result isn't available within `timeout` seconds. If the result is already available, it's returned immediately with no blocking. – ShadowRanger Aug 16 '19 at 19:30