I was playing around async code lately, when I tried to debug the code in PyCharm I saw some really strange behaviour I think it's because of the underlying architectureimport asyncio. This is the code I'm talking about.
async def compute(x, y):
print("Compute %s + %s ..." % (x, y))
await asyncio.sleep(1.0)
return x + y
tasks = [compute(x,x) for x in range(10)]
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
It's strange because when I set breakpoint inside the coroutine execution is never breaked and whole code completes running easily besides this I don't get much details of event loop(except some mess in the stack).
So here are my questions
Double-clicking an active or awaiting task shows the async call stack in the Call Stack window. To understand which thread is running a specific task, you can swap between the Parallel Threads and Parallel Tasks windows. You can do this by right-clicking and selecting Go To Thread in the context menu.
An async function uses the await keyword to denote a coroutine. When using the await keyword, coroutines release the flow of control back to the event loop. To run a coroutine, we need to schedule it on the event loop. After scheduling, coroutines are wrapped in Tasks as a Future object.
Since Python 3.5, it is possible to use asynchronism in your scripts. This evolution allowed the use of new keywords async and await along with the new module asyncio. Async and Await were firstly introduced in C#, in order to structure non-blocking code in a similar fashion as you would write blocking code.
The async stuff isn't thread safe because it doesn't need to be. Async code is all occurring in the same thread, so it isn't possible to preempt with another one, context switching only occurs at await calls.
Just to add here as sample here:
async def compute(x, y):
print("Compute %s + %s ..." % (x, y))
await asyncio.sleep(1.0) # add breakpoint here and then run it in debug mode
return x + y
tasks = [compute(x,x) for x in range(10)]
loop = asyncio.get_event_loop()
loop.set_debug(True)
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
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