2024-08-16 21:38:22 +08:00
|
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
"""
|
|
|
|
|
共享内存模块。类似于redis,但是更加轻量级并且线程安全
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
import threading
|
2024-08-17 19:10:03 +08:00
|
|
|
|
from typing import Any, Optional
|
2024-08-16 21:38:22 +08:00
|
|
|
|
|
|
|
|
|
from liteyuki.comm.channel import Channel
|
2024-08-16 21:44:27 +08:00
|
|
|
|
from liteyuki.utils import IS_MAIN_PROCESS
|
2024-08-16 21:38:22 +08:00
|
|
|
|
|
|
|
|
|
if IS_MAIN_PROCESS:
|
|
|
|
|
_locks = {}
|
|
|
|
|
|
|
|
|
|
|
2024-08-16 21:44:27 +08:00
|
|
|
|
def _get_lock(key) -> threading.Lock:
|
|
|
|
|
"""
|
|
|
|
|
获取锁
|
|
|
|
|
"""
|
2024-08-16 21:38:22 +08:00
|
|
|
|
if IS_MAIN_PROCESS:
|
|
|
|
|
if key not in _locks:
|
|
|
|
|
_locks[key] = threading.Lock()
|
|
|
|
|
return _locks[key]
|
|
|
|
|
else:
|
|
|
|
|
raise RuntimeError("Cannot get lock in sub process.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class KeyValueStore:
|
|
|
|
|
def __init__(self):
|
|
|
|
|
self._store = {}
|
2024-08-17 19:10:03 +08:00
|
|
|
|
self.active_chan = Channel[tuple[str, Optional[dict[str, Any]]]](_id="shared_memory-active")
|
|
|
|
|
self.passive_chan = Channel[tuple[str, Optional[dict[str, Any]]]](_id="shared_memory-passive")
|
2024-08-16 21:38:22 +08:00
|
|
|
|
|
2024-08-17 19:10:03 +08:00
|
|
|
|
def set(self, key: str, value: Any) -> None:
|
2024-08-16 21:43:29 +08:00
|
|
|
|
"""
|
|
|
|
|
设置键值对
|
|
|
|
|
Args:
|
|
|
|
|
key: 键
|
|
|
|
|
value: 值
|
|
|
|
|
|
|
|
|
|
"""
|
2024-08-16 21:38:22 +08:00
|
|
|
|
if IS_MAIN_PROCESS:
|
|
|
|
|
lock = _get_lock(key)
|
|
|
|
|
with lock:
|
|
|
|
|
self._store[key] = value
|
|
|
|
|
else:
|
|
|
|
|
# 向主进程发送请求拿取
|
2024-08-17 19:10:03 +08:00
|
|
|
|
self.passive_chan.send(
|
|
|
|
|
(
|
|
|
|
|
"set",
|
|
|
|
|
{
|
|
|
|
|
"key" : key,
|
|
|
|
|
"value": value
|
|
|
|
|
}
|
|
|
|
|
)
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
def get(self, key: str, default: Optional[Any] = None) -> Optional[Any]:
|
2024-08-16 21:43:29 +08:00
|
|
|
|
"""
|
|
|
|
|
获取键值对
|
|
|
|
|
Args:
|
|
|
|
|
key: 键
|
|
|
|
|
default: 默认值
|
|
|
|
|
|
|
|
|
|
Returns:
|
2024-08-17 19:10:03 +08:00
|
|
|
|
Any: 值
|
2024-08-16 21:43:29 +08:00
|
|
|
|
"""
|
2024-08-16 21:38:22 +08:00
|
|
|
|
if IS_MAIN_PROCESS:
|
|
|
|
|
lock = _get_lock(key)
|
|
|
|
|
with lock:
|
|
|
|
|
return self._store.get(key, default)
|
|
|
|
|
else:
|
2024-08-17 19:10:03 +08:00
|
|
|
|
recv_chan = Channel[Optional[Any]]("recv_chan")
|
|
|
|
|
self.passive_chan.send(
|
|
|
|
|
(
|
|
|
|
|
"get",
|
|
|
|
|
{
|
|
|
|
|
"key" : key,
|
|
|
|
|
"default" : default,
|
|
|
|
|
"recv_chan": recv_chan
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
)
|
|
|
|
|
)
|
|
|
|
|
return recv_chan.receive()
|
2024-08-16 21:38:22 +08:00
|
|
|
|
|
2024-08-16 21:43:29 +08:00
|
|
|
|
def delete(self, key: str, ignore_key_error: bool = True) -> None:
|
|
|
|
|
"""
|
|
|
|
|
删除键值对
|
|
|
|
|
Args:
|
|
|
|
|
key: 键
|
|
|
|
|
ignore_key_error: 是否忽略键不存在的错误
|
|
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
|
"""
|
2024-08-16 21:38:22 +08:00
|
|
|
|
if IS_MAIN_PROCESS:
|
|
|
|
|
lock = _get_lock(key)
|
|
|
|
|
with lock:
|
|
|
|
|
if key in self._store:
|
2024-08-16 21:43:29 +08:00
|
|
|
|
try:
|
|
|
|
|
del self._store[key]
|
|
|
|
|
del _locks[key]
|
|
|
|
|
except KeyError as e:
|
|
|
|
|
if not ignore_key_error:
|
|
|
|
|
raise e
|
2024-08-16 21:38:22 +08:00
|
|
|
|
else:
|
|
|
|
|
# 向主进程发送请求删除
|
2024-08-17 19:10:03 +08:00
|
|
|
|
self.passive_chan.send(
|
|
|
|
|
(
|
|
|
|
|
"delete",
|
|
|
|
|
{
|
|
|
|
|
"key": key
|
|
|
|
|
}
|
|
|
|
|
)
|
|
|
|
|
)
|
2024-08-16 21:38:22 +08:00
|
|
|
|
|
2024-08-17 19:10:03 +08:00
|
|
|
|
def get_all(self) -> dict[str, Any]:
|
2024-08-16 21:43:29 +08:00
|
|
|
|
"""
|
|
|
|
|
获取所有键值对
|
|
|
|
|
Returns:
|
2024-08-17 19:10:03 +08:00
|
|
|
|
dict[str, Any]: 键值对
|
2024-08-16 21:43:29 +08:00
|
|
|
|
"""
|
2024-08-16 21:38:22 +08:00
|
|
|
|
if IS_MAIN_PROCESS:
|
|
|
|
|
return self._store
|
|
|
|
|
else:
|
2024-08-17 19:10:03 +08:00
|
|
|
|
recv_chan = Channel[dict[str, Any]]("recv_chan")
|
|
|
|
|
self.passive_chan.send(
|
|
|
|
|
(
|
|
|
|
|
"get_all",
|
|
|
|
|
{
|
|
|
|
|
"recv_chan": recv_chan
|
|
|
|
|
}
|
|
|
|
|
)
|
|
|
|
|
)
|
|
|
|
|
return recv_chan.receive()
|
2024-08-16 23:43:43 +08:00
|
|
|
|
|
|
|
|
|
|
2024-08-16 21:38:22 +08:00
|
|
|
|
class GlobalKeyValueStore:
|
|
|
|
|
_instance = None
|
|
|
|
|
_lock = threading.Lock()
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def get_instance(cls):
|
|
|
|
|
if IS_MAIN_PROCESS:
|
|
|
|
|
if cls._instance is None:
|
|
|
|
|
with cls._lock:
|
|
|
|
|
if cls._instance is None:
|
|
|
|
|
cls._instance = KeyValueStore()
|
|
|
|
|
return cls._instance
|
|
|
|
|
else:
|
|
|
|
|
raise RuntimeError("Cannot get instance in sub process.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# 全局单例访问点
|
|
|
|
|
if IS_MAIN_PROCESS:
|
2024-08-17 19:10:03 +08:00
|
|
|
|
shared_memory: KeyValueStore = GlobalKeyValueStore.get_instance()
|
2024-08-16 21:38:22 +08:00
|
|
|
|
|
2024-08-17 19:12:11 +08:00
|
|
|
|
|
2024-08-16 21:38:22 +08:00
|
|
|
|
@shared_memory.passive_chan.on_receive(lambda d: d[0] == "get")
|
2024-08-17 19:12:11 +08:00
|
|
|
|
def on_get(data: tuple[str, dict[str, Any]]):
|
|
|
|
|
key = data[1]["key"]
|
|
|
|
|
default = data[1]["default"]
|
|
|
|
|
recv_chan = data[1]["recv_chan"]
|
|
|
|
|
recv_chan.send(shared_memory.get(key, default))
|
2024-08-16 21:38:22 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@shared_memory.passive_chan.on_receive(lambda d: d[0] == "set")
|
2024-08-17 19:12:11 +08:00
|
|
|
|
def on_set(data: tuple[str, dict[str, Any]]):
|
|
|
|
|
key = data[1]["key"]
|
|
|
|
|
value = data[1]["value"]
|
|
|
|
|
shared_memory.set(key, value)
|
2024-08-16 21:38:22 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@shared_memory.passive_chan.on_receive(lambda d: d[0] == "delete")
|
2024-08-17 19:12:11 +08:00
|
|
|
|
def on_delete(data: tuple[str, dict[str, Any]]):
|
|
|
|
|
key = data[1]["key"]
|
|
|
|
|
shared_memory.delete(key)
|
2024-08-16 21:43:29 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@shared_memory.passive_chan.on_receive(lambda d: d[0] == "get_all")
|
2024-08-17 19:12:11 +08:00
|
|
|
|
def on_get_all(data: tuple[str, dict[str, Any]]):
|
|
|
|
|
recv_chan = data[1]["recv_chan"]
|
|
|
|
|
recv_chan.send(shared_memory.get_all())
|
|
|
|
|
|
2024-08-16 21:38:22 +08:00
|
|
|
|
else:
|
2024-08-17 00:18:06 +08:00
|
|
|
|
# 子进程在入口函数中对shared_memory进行初始化
|
2024-08-17 19:12:11 +08:00
|
|
|
|
shared_memory: Optional[KeyValueStore] = None # type: ignore
|
2024-08-16 21:38:22 +08:00
|
|
|
|
|
2024-08-17 00:18:06 +08:00
|
|
|
|
_ref_count = 0 # import 引用计数, 防止获取空指针
|
2024-08-16 21:38:22 +08:00
|
|
|
|
if not IS_MAIN_PROCESS:
|
|
|
|
|
if (shared_memory is None) and _ref_count > 1:
|
|
|
|
|
raise RuntimeError("Shared memory not initialized.")
|
|
|
|
|
_ref_count += 1
|