panda3d icon indicating copy to clipboard operation
panda3d copied to clipboard

Add async/await based sleep, timeout and waiting functions

Open el-dee opened this issue 3 years ago • 2 comments

Description

Asyncio provides a bunch of functions to perform various task related functions that are, unless I'm mistaken, still missing in Panda3D implementation of async/await :

  • sleep() : blocks the current task for x seconds
  • wait_for() : Wait that the given coro/task is done with a timeout
  • wait() : Run the given coro/futures and await their completion
  • as_completed() : Run the given coro/futures and return an iterator that can be awaited sequentially

Use Case

These functions are useful to implement more complex behaviours in asynchronous code that would otherwise be cumbersome to implement. For example, as_completed() can be used to update a progress bar as several parallel tasks are completed.

wait_for() helps to have a timeout limit on a given task without having to create another tasks that will cancel the awaited task.

wait() can be used to have better control than gather() which run unconditionally

Implementation

These function could be implemented using the existing Panda3d code. Here is an implementation for sleep (heavily based on the actual asyncio implementation) that uses Panda3D classes :

async def sleep(delay):
    future = AsyncFuture()
    h = taskMgr.do_method_later(delay, future.set_result, None, extraArgs=[None])
    try:
        return await future
    finally:
        h.cancel()

(The code should completed to take care of a potential cancel of the coro)

el-dee avatar May 20 '21 21:05 el-dee