Issue
I'm new to asyncio. Reading asyncio documentation, I don't understand where Tasks are run.
import asyncio
async def query_api(url):
#http://a.b.c takes 3 seconds
#http://x.y.z takes 5 seconds
async def main():
task1 = asyncio.create_task(query_api('http://a.b.c'))
task2 = asyncio.create_task(query_api('http://x.y.z'))
await task1
await task2
print ('Tasks Done')
asyncio.run(main())
This doc says asyncio has an event loop running in a main thread.
- Do
task1
andtask2
run in the main thread? If so, they must not run in parallel because CPU can only do one thing at a time? Tasks Done
appears after 8 seconds or sooner?
Solution
AsyncIO is a framework to run concurrent
tasks. Please note that Concurrency does not mean parallelism here.
- Do task1 and task2 run in the main thread? If so, they must not run in parallel because CPU can only do one thing at a time?
Yes. They run in the same thread (by default) and it means that the they use the same CPU. But the trick is that we do not need to hold on to the CPU while we are doing network I/O.
Task2 can start using the CPU when Task1 is waiting on network to respond.
- Tasks Done appears after 8 seconds or sooner?
The tasks should finish before 8 seconds
There are ways to use multi-threading or multi-processing using asyncIO if you require your tasks to be run outside your main thread.
Answered By - srj
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.