Yolov/global_data.py

52 lines
1.4 KiB
Python
Raw Normal View History

2025-12-11 13:41:07 +08:00
# global_data.py
import threading
2025-11-26 13:55:04 +08:00
2025-12-11 13:41:07 +08:00
class GlobalData:
"""全局数据管理类,支持多任务"""
2025-11-26 13:55:04 +08:00
2025-12-11 13:41:07 +08:00
def __init__(self):
self._init()
2025-11-26 13:55:04 +08:00
2025-12-11 13:41:07 +08:00
def _init(self):
"""初始化全局字典和锁"""
self._global_dict = {}
#self._lock = threading.Lock() # 原代码
self._lock = threading.RLock() # 使用可重入锁
2025-11-26 13:55:04 +08:00
2025-12-11 13:41:07 +08:00
def set_value(self, name, value):
"""设置全局值"""
with self._lock:
self._global_dict[name] = value
def get_value(self, name, defValue=None):
"""获取全局值"""
with self._lock:
try:
return self._global_dict[name]
except KeyError:
return defValue
def get_or_create_dict(self, name):
"""获取或创建字典"""
with self._lock:
if name not in self._global_dict:
self._global_dict[name] = {}
return self._global_dict[name]
def remove_value(self, name):
"""移除全局值"""
with self._lock:
if name in self._global_dict:
del self._global_dict[name]
def clear_all_tasks(self):
"""清除所有任务"""
with self._lock:
for key in list(self._global_dict.keys()):
if key.startswith('task_'):
del self._global_dict[key]
# 创建全局实例
gd = GlobalData()