原文地址
没有使用锁时
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| class A:
def __init__(self): self.a = 1
async def run(self): self.a += 1 await asyncio.sleep(1) self.a -= 1 print(self.a)
a = A()
loop = asyncio.get_event_loop() loop.run_until_complete(asyncio.gather(a.run(), a.run(), a.run(), a.run()))
|
使用锁时
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| import asyncio
class A:
def __init__(self): self.a = 1 self.lock = asyncio.Lock()
async def run(self): async with self.lock: self.a += 1 await asyncio.sleep(1) self.a -= 1 print(self.a)
a = A()
loop = asyncio.get_event_loop() loop.run_until_complete(asyncio.gather(a.run(), a.run(), a.run(), a.run()))
|
引用同事的话,在使用一个公用变量的时候,中途要await把当前线程的执行权放出去,但又不希望其他协程来访问或者修改这个公共变量的时候,就要用锁了,如果中途没有await释放控制权,那其实不用加锁,因为协程是手动控制释放执行权的,不手动释放的话,其他协程是插不进来的