1 回答

TA貢獻1851條經驗 獲得超4個贊
您不能將 a 傳遞threading.Lock
給async with
,因為它不是為異步使用而設計的,它是一個阻塞原語。更重要的是,async with threading.Lock()
即使它確實有效也沒有意義,因為您將獲得一把全新的鎖,它總是會成功。為了使鎖定有意義,您必須在多個線程之間共享一個鎖,例如存儲在對象的屬性中,或以另一種方式與對象相關聯。這個答案的其余部分將假設您在threading.Lock
線程之間共享。
由于threading.Lock
總是阻塞,因此您可以從 asyncio 使用它的唯一方法是在專用線程中獲取它,暫停當前協程的執行,直到獲取鎖。此功能已包含在run_in_executor
事件循環方法中,您可以應用該方法:
_pool = concurrent.futures.ThreadPoolExecutor()
async def work(lock, other_args...):
? ? # lock is a threading.Lock shared between threads
? ? loop = asyncio.get_event_loop()
? ? # Acquire the lock in a worker thread, suspending us while waiting.
? ? await loop.run_in_executor(_pool, lock.acquire)
? ? ... access the object with the lock held ...
? ? # Can release directly because release() doesn't block and a
? ? # threading.Lock can be released from any thread.
? ? lock.release()
您可以通過創建異步上下文管理器來使其使用起來更優雅(并且異常安全):
_pool = concurrent.futures.ThreadPoolExecutor()
@contextlib.asynccontextmanager
async def async_lock(lock):
? ? loop = asyncio.get_event_loop()
? ? await loop.run_in_executor(_pool, lock.acquire)
? ? try:
? ? ? ? yield? # the lock is held
? ? finally:
? ? ? ? lock.release()
然后你可以按如下方式使用它:
# lock is a threading.Lock shared between threads
async with async_lock(lock):
? ? ... access the object with the lock held ...
當然,在 asyncio 之外你不會使用其中的任何一個,你只是直接獲取鎖:
# lock is a threading.Lock shared between threads
with lock:
? ?... access the object ...
請注意,我們使用單獨的線程池而不是傳遞None給run_in_executor()重用默認池。這是為了避免在持有鎖的函數本身需要訪問線程池以供其他用途的情況下出現死鎖run_in_executor()。通過保持線程池私有,我們避免了因其他人使用同一池而導致死鎖的可能性。
添加回答
舉報