I need a Future object in python3.
Python has two built in implementation:
asyncio module has one, but its not suitable for my application.
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With