优化一下锁的使用

This commit is contained in:
Yun
2025-04-14 17:03:32 +08:00
parent f66e76883f
commit 175e36ebd7
+6 -6
View File
@@ -16,7 +16,7 @@ type langx struct {
ops *options ops *options
codeMap map[string]int codeMap map[string]int
transMap map[string]map[string]string transMap map[string]map[string]string
mut sync.Mutex mut sync.RWMutex
} }
var l *langx = &langx{} var l *langx = &langx{}
@@ -27,7 +27,7 @@ func init() {
ops: defaultOptions(), ops: defaultOptions(),
codeMap: make(map[string]int), codeMap: make(map[string]int),
transMap: make(map[string]map[string]string), transMap: make(map[string]map[string]string),
mut: sync.Mutex{}, mut: sync.RWMutex{},
} }
} }
@@ -211,8 +211,8 @@ func GetTransFormatCtx(ctx context.Context, key string, format map[string]string
// 根据Key获取code // 根据Key获取code
func GetCode(key string) int { func GetCode(key string) int {
l.mut.Lock() l.mut.RLock()
defer l.mut.Unlock() defer l.mut.RUnlock()
code, ok := l.codeMap[key] code, ok := l.codeMap[key]
if !ok { if !ok {
return l.ops.defaultCode return l.ops.defaultCode
@@ -222,8 +222,8 @@ func GetCode(key string) int {
// 获取翻译 // 获取翻译
func GetMsg(lang string, key string) string { func GetMsg(lang string, key string) string {
l.mut.Lock() l.mut.RLock()
defer l.mut.Unlock() defer l.mut.RUnlock()
// 找指定语言 // 找指定语言
str, ok := l.transMap[lang] str, ok := l.transMap[lang]
if ok { if ok {