【发布时间】:2018-12-05 06:18:33
【问题描述】:
我很难弄清楚为什么取消注释 await asyncio.sleep(1) 会导致 Test 被打印 10 次。使用异步时,val 属性的初始化似乎失败了。
不应该尊重初始化并只打印一次,因为它是同一个实例。当存在awaitable 呼叫时如何解决此问题?
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))
【问题讨论】:
标签: python async-await python-asyncio