with
オブジェクトを貸与し、ステートメントのスコープが終了したときにオブジェクトを取り戻す、制御された種類の「ライブラリ」として機能するPythonコンテキストマネージャーを作成したいと考えています。
疑似コードでは、次のようなことを考えていました。
class Library:
def __init__(self):
self.lib = [1,2,3,4]
self.lock = Condition(Lock())
def __enter__(self):
with self.lock:
# Somehow keep track of this object-thread association
if len(self.lib) > 0:
return self.lib.pop()
else:
self.lock.wait()
return self.lib.pop()
def __exit__(self):
with self.lock:
# Push the object that the calling thread obtained with
# __enter__() back into the array
self.lock.notify()