Issue
I am having some trouble to figure out why uncommenting the await asyncio.sleep(1)
causes Test
to be printed 10 times. It seems that the initialization of val
attribute is failing when using async.
Shouldn't the initialization be respected and print only once, as it is the same instance. How can address this behavior when awaitable
calls are present?
class TestAsync:
def __init__(self):
self.val = None
async def some_fun(self):
if not self.val:
# await asyncio.sleep(1) # Magic line
print('Test')
self.val = 10
async def main(loop):
a = TestAsync()
tasks = [a.some_fun() for _ in range(10)]
return await asyncio.gather(*tasks)
if __name__ == '__main__':
cur_loop = asyncio.get_event_loop()
cur_loop.run_until_complete(main(cur_loop))
Solution
asyncio
doesn't let you stop thinking about concurrency issues. You're running into pretty much exactly the same issue you would have had with threads.
Each some_fun
coroutine that sees a falsy value of self.val
continues into the body of the if
statement. How many coroutines see such a value depends on how many coroutines reach the if
test before one of them sets self.val
to 10
.
Without the sleep
, the first coroutine sets self.val
to 10
immediately, without giving any others a chance to intervene. With the sleep
, each coroutine goes to sleep and lets others run, and all of them see None
before any of them changes the value.
Answered By - user2357112 supports Monica
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.