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!

2
  • This post may answer your question. Commented Aug 16, 2019 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 Commented Aug 16, 2019 at 14:28

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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: The docs cover this already; 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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.