Skip to content
This repository has been archived by the owner on Jun 4, 2023. It is now read-only.

feature_futures

Irmen de Jong edited this page Apr 18, 2016 · 3 revisions

Futures.

Say you have a function that takes a while to compute, and you don't want to wait until it is finished. You want to continue doing other things while the function is computing its result. You could start using threading, multiprocessing or perhaps concurrent.futures from the standard library but when you have Pyro installed you have another option:

Pyro provides a Future object that lets you easily turn this function in some form of asynchronous call. The call will be started but runs in the background, and you can retrieve the result once it is finished. In the meantime you can do your own business. It's possible to check on the asynchronous result to see if it's done yet.

You can use it for any function within or outside the scope of Pyro itself. Pyro does use it for its own async remote calls, which are discussed somewhere else.

A few things to know about:

  • async here is something else entirely as asynchronous (or non-blocking) I/O and Python's asyncio module. Don't confuse it with those. In the context here it simply means that the function is running in the background (using a simple worker thread) and that you can grab the result of it later on.
  • Pyro's Future class is similar to but not compatible with the Future from the Python standard library.

Relevant references:

Example code:

import time
import Pyro4


def slow_function(a, b):
    time.sleep(4)  # assume this is a function that takes some time to compute.
    return a+b


def completion_callback(value):
    print("[Callback! The result seems to be ready: {0}]".format(value))
    return value * 2  # can do additional processing on the result from the future


# normal call, will take a while to complete
result = slow_function(4, 5)


# call using Future
func = Pyro4.Future(slow_function)
result = func(4, 5).then(completion_callback)

# result is now a FutureResult
# we can continue doing other stuff in the meantime
time.sleep(1)

print(result.ready)    # check if result is ready
print(result.wait(1))  # wait max 1 sec, see if it's ready now
print(result.value)    # wait until result is ready and get it

Output:

  <...delay...>
False
  <...delay...>
False
  <...delay...>
[Callback! The result seems to be ready: 9]
18
Clone this wiki locally