Python - Implementing a Future object

Viewed 1406

I need a Future object in python3.

Python has two built in implementation:

  1. asyncio module has one, but its not suitable for my application.

  2. concurrent.futures has one, but its documentation state that this object should be created only by Executor objects:

The following Future methods are meant for use in unit tests and Executor implementations.

https://docs.python.org/3/library/concurrent.futures.html#future-objects

The basic interface is:

class Future:
   def get(self):
       pass
   def set(self, val):
       pass

While the key here is that if get is called before set, the method blocks until value is set.

set is setting the value and releasing any thread that is waiting on get.

Is it safe to use one of the built-in implementation above in a multithreaded application?

How to implement that efficiently?

2 Answers

With the guidance of @SolomonSlow i implemented this code:

from threading import Lock, Condition

class Future:
    def __init__(self):
        self.__condition = Condition(Lock())
        self.__val = None
        self.__is_set = False

    def get(self):
        with self.__condition:
            while not self.__is_set:
                self.__condition.wait()
            return self.__val

    def set(self, val):
        with self.__condition:
            if self.__is_set:
                raise RuntimeError("Future has already been set")
            self.__val = val
            self.__is_set = True
            self.__condition.notify_all()

    def done(self):
        return self.__is_set

Any suggestions are welcome.

How to implement that efficiently?

I don't know about efficiently, but simply:

Sounds like a class with a value member, an is_set member, and a lock and a condition. The set() method should

  • lock the lock
  • raise an error if is_set already is true, or else
    • is_set = True
    • set the value
    • condition.notifyAll()

The get() method should lock the lock and then loop waiting on the condition variable until is_set is True, and finally, return the value.

If there's a more efficient way to do it with pure Python code, that's beyond my ken.

Related