52 lines
1.3 KiB
Python
52 lines
1.3 KiB
Python
# global_data.py
|
|
import threading
|
|
|
|
|
|
class GlobalData:
|
|
"""全局数据管理类,支持多任务"""
|
|
|
|
def __init__(self):
|
|
self._init()
|
|
|
|
def _init(self):
|
|
"""初始化全局字典和锁"""
|
|
self._global_dict = {}
|
|
self._lock = threading.Lock()
|
|
|
|
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()
|