I have code like the following:
class SomeSharedData(object):
def __init__(self):
self._lock = RLock()
self._errors = 0
@property
def errors(self):
with self._lock:
return self._errors
@errors.setter
def errors(self, value):
with self._lock:
self._errors = value
Except with more properties like errors
. My goal here is ease-of-use, and not efficiency, so the excessive locking is fine.
Is there a more concise way of defining these properties?
The best I've come up with so far is this:
class thread_safe_property(object):
def __init__(self, name=None):
self.name = name
def __get__(self, obj, objtype):
with obj._lock:
return getattr(obj, self.name)
def __set__(self, obj, val):
with obj._lock:
setattr(obj, self.name, val)
class SomeSharedData(object):
def __init__(self):
self._lock = RLock()
self._errors = 0
errors = thread_safe_property('_errors')
Ideas? Better Ways?
Both the original code and the new approach suffer from possible race conditions on statements like data.errors += 1
, but I rarely need to perform those operations so I add workarounds where needed.
Thank you!