uasyncio: number of tasks in the event loop

Discussion about programs, libraries and tools that work with MicroPython. Mostly these are provided by a third party.
Target audience: All users and developers of MicroPython.
Post Reply
Jim.S
Posts: 84
Joined: Fri Dec 18, 2015 7:36 pm

uasyncio: number of tasks in the event loop

Post by Jim.S » Sun Apr 15, 2018 12:00 pm

Is there a simple way to get the number of tasks queued in the event loop?

I think I have written a program that adds a new task every time one task is run, and need to check my understanding of what is happening.

User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: uasyncio: number of tasks in the event loop

Post by pythoncoder » Mon Apr 16, 2018 7:49 am

The uasyncio V2.0 EventLoop class maintains two queues: runq and waitq. The former holds tasks which are ready to run, while the latter holds ones which are waiting pending later execution. In general you can get the total number of tasks with

Code: Select all

loop = asyncio.get_event_loop()
ntasks = len(loop.runq) + len(loop.waitq)
However if you're using the methods which schedule callback functions rather than coroutines (e.g. call_soon) the length of runq can be overstated because the args to the callback are also placed on the queue. So each callback which is ready for execution but hasn't yet been run will occupy two entries.

If you're just using coroutines I think you'll be OK.
Peter Hinch
Index to my micropython libraries.

Jim.S
Posts: 84
Joined: Fri Dec 18, 2015 7:36 pm

Re: uasyncio: number of tasks in the event loop

Post by Jim.S » Sat Apr 21, 2018 4:12 pm

Thanks @Pythoncoder, works nicely. But anyone having problems getting it to work should make sure they are using uasyncio 2.0 and hence the latest pyboard firmware (which we should all be doing anyway!). My first attempt failed because I was using uasyncio 1.0. And it is my understanding that uasyncio 2.0 will only work with late 1.9.3 firmware.

(My original problem, [i,e. creating an extra task every loop until I exceeded the maximum number of tasks] was caused by a spelling mistake in the boolean variable that should have only allowed one task to be created. Now, at work I use the Enthought Canopy editor with automatic checking of variable names that would have recognised this error. At home, I use Idle, which is pleasantly simple, but limited in checking)

User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: uasyncio: number of tasks in the event loop

Post by pythoncoder » Sun Apr 22, 2018 9:12 am

A good tool for error checking and PEP8 compliance is pylint.
Peter Hinch
Index to my micropython libraries.

Post Reply