盡管asyncio庫是使用單線程來實作協程的,但是它還是并發的,亂序執行的。可以說是單線程的排程系統,并且由于執行時有延時或者I/O中斷等因素,每個協程如果同步時,還是得使用一些同步對象來實作。
比如asyncio就定義了一個鎖對象Lock,它一次隻允許一個協程來通路共享的資源,如果多協程想通路就會阻塞起來,也就是說如果一個協程沒有釋放這個鎖,别的協程是沒有辦法通路共享的資源。
例子:
import asyncio
import functools
def unlock(lock):
print('callback releasing lock')
lock.release()
async def coro1(lock):
print('coro1 waiting for the lock')
with await lock:
print('coro1 acquired lock')
print('coro1 released lock')
async def coro2(lock):
print('coro2 waiting for the lock')
await lock
try:
print('coro2 acquired lock')
finally:
print('coro2 released lock')
lock.release()
async def main(loop):
# Create and acquire a shared lock.
lock = asyncio.Lock()
print('acquiring the lock before starting coroutines')
await lock.acquire()
print('lock acquired: {}'.format(lock.locked()))
# Schedule a callback to unlock the lock.
loop.call_later(0.1, functools.partial(unlock, lock))
# Run the coroutines that want to use the lock.
print('waiting for coroutines')
await asyncio.wait([coro1(lock), coro2(lock)]),
event_loop = asyncio.get_event_loop()
try:
event_loop.run_until_complete(main(event_loop))
finally:
event_loop.close()
輸出結果如下:
acquiring the lock before starting coroutines
lock acquired: True
waiting for coroutines
coro1 waiting for the lock
coro2 waiting for the lock
callback releasing lock
coro1 acquired lock
coro1 released lock
coro2 acquired lock
coro2 released lock
以上這篇在python裡協程使用同步鎖Lock的執行個體就是小編分享給大家的全部内容了,希望能給大家一個參考,也希望大家多多支援我們。
本文标題: 在python裡協程使用同步鎖Lock的執行個體
本文位址: http://www.cppcns.com/jiaoben/python/252780.html