尝试创建一个可以使用 threading.lock 锁定对象的类:
class ObjectLock(object):
def __init__(self):
self._lock = threading.Lock()
self._value = False
def __str__(self):
self.acquire()
try:
if(self._value):
return self._value
else:
return self._value
finally:
self.release()
def __enter__(self):
self.acquire()
def __exit__(self, type, value, traceback):
self.release()
def acquire(self):
self._lock.acquire()
def release(self):
self._lock.release()
def locked(self):
return self._lock.locked()
lock = ObjectLock()
print(lock)
with lock:
print (lock)
问题是我正在尝试实施“with”。如果在“with”块中调用方法(例如str,则重新获取锁......这很糟糕。当我知道我在锁中工作时,我是否必须创建一组单独的方法来调用?