niming_igapi/utils/ThreadSafeOrderedDict.py

48 lines
1.2 KiB
Python
Raw Permalink Normal View History

2024-12-18 00:35:17 +08:00
from collections import OrderedDict
from threading import RLock
class ThreadSafeOrderedDict:
def __init__(self):
self.lock = RLock()
self.data = OrderedDict()
def __setitem__(self, key, value):
with self.lock:
self.data[key] = value
def __getitem__(self, key):
with self.lock:
if key in self.data:
return self.data[key]
return None
def remove(self, key):
with self.lock:
if key in self.data:
del self.data[key]
def move_to_end(self, key, last=True):
with self.lock:
if key in self.data:
self.data.move_to_end(key, last=last)
def pop(self, key):
with self.lock:
if key in self.data:
return self.data.pop(key)
return None
def popitem(self, last:bool=True):
with self.lock:
if len(self.data):
return self.data.popitem(last)
return None
def items(self):
with self.lock:
return self.data.items()
def __repr__(self):
with self.lock:
return repr(self.data)