I'm running into some strange errors with initialising Locks and running asynchronous code. Suppose we had a class to use with some resource protected by a lock.
import asyncio
class C:
def __init__(self):
self.lock = asyncio.Lock()
async def foo(self):
async with self.lock:
return 'foo'
def async_foo():
c = C()
asyncio.run(c.foo())
if __name__ == '__main__':
async_foo()
async_foo()
This throws an error when run. It occurs on lock initialisation in init
.
RuntimeError: There is no current event loop in thread 'MainThread'.
So duplicating the asyncio.run
call in the function does not have this effect. It seems that the object needs to be initialised multiple times. It is also not enough to instantiate multiple locks in a single constructor. So perhaps it has something to do with the event loops state after asyncio.run
is called.
What is going on? And how could I modify this code to work? Let me also clarify a bit, the instance is created outside asyncio.run
and async functions for a reason. I'd like for it to be usable elsewhere too. If that makes a difference.
Alternatively, can threading.Lock
be used for async things also? It would have the added benefit of being thread-safe, which asyncio.Lock
reportedly is not.