您好,登錄后才能下訂單哦!
盡管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的實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。