earwax.promises.threaded_promise module¶
Provides the ThreadedPromise class.
-
class
earwax.promises.threaded_promise.
ThreadedPromise
(thread_pool: concurrent.futures._base.Executor, func: Optional[Callable[[...], T]] = None, future: Optional[concurrent.futures._base.Future] = None)¶ Bases:
earwax.promises.base.Promise
A promise that a value will be available in the future.
Uses an
Executor
subclass (likeThreadPoolExecutor
, orProcessPoolExecutor
for threading).You can create this class directly, or by using decorators.
Here is an example of the decorator syntax:
from concurrent.futures import ThreadPoolExecutor promise: ThreadedPromise = ThreadedPromise(ThreadPoolExecutor()) @promise.register_func def func() -> None: # Long-running task... return 5 @promise.event def on_done(value: int) -> None: # Do something with the return value. @promise.event def on_error(e: Exception) -> None: # Do something with an error. @promise.event def on_finally(): print('Done.') promise.run()
Or you could create the promise manually:
promise = ThreadedPromise( ThreadPoolExecutor(), func=predefined_function ) promise.event('on_done')(print) promise.run()
Note the use of Pyglet’s own event system.
Variables: - thread_pool – The thread pool to use.
- func – The function to submit to the thread pool.
- future – The future that is running, or None
if the
run()
method has not yet been called.
-
cancel
() → None¶ Try to cancel
self.future
.If There is no future,
RuntimeError
will be raised.
-
check
(dt: float) → None¶ Check state and react accordingly.
Checks to see if
self.future
has finished or not.If it has, dispatch the
on_done()
event with the resulting value.If an error has been raised, dispatch the
on_error()
event with the resulting error.If either of these things have happened, dispatch the
on_finally()
event.Parameters: dt – The time since the last run.
This argument is required by
pyglet.clock.schedule
.
-
register_func
(func: Callable[[...], T]) → Callable[[...], T]¶ Register promise function.
Registers the function to be called by the
run()
method.Parameters: func – The function to use. Will be stored in self.func
.
-
run
(*args, **kwargs) → None¶ Start this promise running.
The result of calling
submit
onself.thread_pool
will be stored onself.future
.If this instance does not have a function registered yet,
RuntimeError
will be raised.Parameters: - args – The extra positional arguments to pass along to
submit
. - kwargs – The extra keyword arguments to pass along to
submit
.
- args – The extra positional arguments to pass along to