Page 2 of 2

Re: Equivalent to asyncio.gather()

Posted: Sat Jan 20, 2018 11:10 am
by cefn
That's really helpful, @pythoncoder.

It helps me understand how new functionality can be layered on your library too, for example providing __iter__ implementation to imply an 'awaitable' signature, use of coro functions (factories) and partial application by passing the coro functions with their arguments into a wrapping class (presumably so that the only reference to the actual coro is 'private' and hence any await invocations are managed properly by the library). Lots to learn from that, thanks.

Task cancellation

Posted: Sat Jan 20, 2018 6:00 pm
by pythoncoder
You might be interested in my approach to task cancellation too. The aim was to enable a coro to pause until a set of tasks had actually completed cancellation and to provide a means of checking the running status of individual tasks. Given the latency which can occur between issuing the pending exception and the actual termination of the task this feedback can be essential in firmware applications.

It took me a while to come up with a solution which is simple in code and easy to use. You can see some example code in asyn_demos.py and some more thorough tests in cantest.py. In essence a cancellable is declared as:

Code: Select all

@asyn.cancellable
async def print_nums(num):
    while True:
        print(num)
        num += 1
        await asyn.sleep(1)
run with

Code: Select all

    loop.create_task(asyn.Cancellable(print_nums, res)())
and cancelled with

Code: Select all

await asyn.Cancellable.cancel_all()
This pauses until all cancellable coros have actually terminated.

There are quite a few options available including organising Cancellable tasks into groups or naming individual Cancellable tasks, but its use can be as simple as above.