Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Implementing a Future object

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?

like image 501
Montoya Avatar asked Oct 14 '25 03:10

Montoya


1 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.

like image 130
Montoya Avatar answered Oct 16 '25 16:10

Montoya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!