I am trying to use asyncio to run multiple tasks "in parallel". There are some critical sections I wanted to protect using an asyncio.Lock().
I found this to work when directly using the eventloop to create the task (i.e. loop.create_task(coro)
). However when I am using the high level function provided by asyncio (asyncio.create_task()
) I am getting errors that the the task would be attached to a different event_loop.
import asyncio
lock = asyncio.Lock()
async def do_something():
while True:
async with lock:
await asyncio.sleep(1)
async def main():
asyncio.create_task(do_something())
asyncio.create_task(do_something())
while True:
await asyncio.sleep(1)
asyncio.run(main())
Traceback (most recent call last):
File "test.py", line 9, in do_something
async with lock:
File "/usr/lib/python3.8/asyncio/locks.py", line 97, in __aenter__
await self.acquire()
File "/usr/lib/python3.8/asyncio/locks.py", line 203, in acquire
await fut
RuntimeError: Task <Task pending name='Task-3' coro=<do_something() running at test.py:9>> got Future <Future pending> attached to a different loop
I would have thought that in this simple example only one eventloop should exist. Can someone explain what is going on here and if there are really multiple loops running?
Thank you a lot!
PS: Not sure if this makes a difference but I ran this on Python 3.7.6 and 3.8.2 under Linux.