我來翻過這需要以下模式功能:如何在Python中使用鎖來保護對象?
from threading import Lock
the_list = []
the_list_lock = Lock()
,並使用它:
with the_list_lock:
the_list.append("New Element")
不幸的是,這並不需要我去獲取鎖,我可以訪問直接對象。我希望對此有所保護(我只是人)。有沒有一個標準的方法來做到這一點?我自己的方法是創建一個HidingLock
類可以這樣使用:
the_list = HidingLock([])
with the_list as l:
l.append("New Element")
但感覺這樣基本的,要麼它應該在標準庫中存在,或者是使用鎖非常非常規的方式。
含義需要一個鎖定的東西之前獲取的訪問?不是真的,你擁有的是預期的解決方案,爲它創建一個接口(即一個類)。而不是直接訪問列表,你可以通過類接口。 – danny
你想保護訪問多遠?如果對象被傳遞給另一個線程,或者在with塊結束後繼續訪問,該怎麼辦? – Dunes
@Dunes:防止意外忘記鎖定。我認爲在Python中不可能做到這一點。 'set'中的 –