Reputation: 13
I am learning about asyncion in Python. There is one confusion that I cannot wrap my head around.
Suppose I have 2 Python scripts: dummy1.py and dummy2.py. In the first script, I have my code written like the following:
loop = asyncio.get_event_loop()
loop.create_task(a_task)
The first script will be imported into the second script, and in the second script, I arrange my code like the following:
loop = asyncio.get_event_loop()
loop.run_forever()
Are there 2 different event loop created? Thanks for your time guys!
Upvotes: 1
Views: 1409
Reputation: 241
The main thing going on with your example is that you only ever started one loop. And when you got the event loop the second time, get_event_loop()
is still pointing to the same loop. The loop still has a pending task as well that will not start until the event loop is running.
The important thing to note about this, is that you have one thread. That threads execution can create tasks, save event loops to variables etc., but once you start the event loop, that thread is now working on that event loop. The code wont continue past the line where you started the loop until it ends. To have multiple event loops you would essentially need multiple threads.
You can see this playout with this example:
import asyncio
async def a_task():
while True:
await asyncio.sleep(5)
print('a_task did something')
loop = asyncio.get_event_loop()
print('Got Event loop in test1.py')
loop.create_task(a_task())
print('Created task in test1.py')
import asyncio
import test1
loop = asyncio.get_event_loop()
print('Got event loop in test2.py')
print('Starting Event loop in test2.py')
loop.run_forever()
print('Event loop ended')
Upvotes: 1