```python
class DataSet:
def __init__(self, sequence_of_numbers):
self._data = tuple(sequence_of_numbers)
@cached_property
def stdev(self):
return statistics.stdev(self._data)
```
`del` can clear the cached property
you can write the property aswell unlike [[property]]
locking is needed in the method for multi-threaded safety
```python
from functools import cached_property
import statistics
import threading
import time
class ThreadSafeDataSet:
def __init__(self, sequence_of_numbers):
self._data = tuple(sequence_of_numbers)
# Create a reentrant lock specific to this instance
self._lock = threading.RLock()
@cached_property
def stdev(self):
# Acquire the lock to ensure only one thread calculates this at a time
with self._lock:
# Double-check pattern: In case another thread calculated it
# while this thread was waiting for the lock.
if "stdev" in self.__dict__:
return self.__dict__["stdev"]
print(
f"[{threading.current_thread().name}] Calculating standard deviation..."
)
# Simulate a heavy calculation if needed, then return
return statistics.stdev(self._data)
# --- Demonstration with Multiple Threads ---
data = ThreadSafeDataSet([10, 12, 23, 23, 16, 23, 21, 16])
def access_stdev():
# Access the cached property from different threads
print(f"[{threading.current_thread().name}] Value is: {data.stdev}")
# Create 3 threads that try to access stdev simultaneously
threads = [
threading.Thread(target=access_stdev, name=f"Thread-{i}") for i in range(3)
]
for t in threads:
t.start()F
for t in threads:
t.join()
```