1
0
mirror of https://github.com/charlienet/go-mixed.git synced 2026-07-14 08:17:26 +08:00

fix: 修复多处并发安全问题及锁实现重构

locker: 导出 RWLocker/EmptyLocker 接口, 新增 WithRWLocker, 重构
  SourceLocker 竞态、Synchronize 数据竞态

collections/linked_list: 补齐 ForEach/Size/GetAt/RemoveAt/ToList
  等方法的锁保护
collections/queue,stack: Peek/Size/IsEmpty 加锁
collections/list/linked_list: Front/Back/GetAt 加锁
maps: rwlock_map.Exist/Count, hash_map.Count 加锁
delay_queue/mem_store: Pop 原子化、Len/IsEmpty 加锁
cleanup_guard: Run() 检查 enable 标志
sets/ketama: 修复接口变更导致的 nil 空指针
This commit is contained in:
Charlie
2026-06-05 10:45:08 +08:00
parent b14262e9eb
commit c44a325384
17 changed files with 178 additions and 82 deletions
+26 -38
View File
@@ -2,20 +2,16 @@ package locker
import (
"context"
"fmt"
"sync/atomic"
redis_store "github.com/charlienet/go-mixed/locker/redis"
"github.com/charlienet/go-mixed/redis"
)
// 带计数器锁
type countLocker struct {
rw rwLocker
Count int32
}
// SourceLocker 资源锁
type SourceLocker struct {
m RWLocker
distributedLocker DistributedLocker
@@ -28,7 +24,7 @@ func NewSourceLocker() *SourceLocker {
locks: make(map[string]*countLocker),
}
l.m.Synchronize()
l.m = NewRWLocker()
return l
}
@@ -43,39 +39,25 @@ func (s *SourceLocker) WithDistributedLocker(distributed DistributedLocker) *Sou
}
func (s *SourceLocker) Lock(key string) {
s.m.RLock()
s.m.Lock()
l, ok := s.locks[key]
s.m.RUnlock()
if ok {
atomic.AddInt32(&l.Count, 1)
l.rw.Lock()
fmt.Println("加锁")
l.Count++
} else {
// 加锁,再次检查是否已经具有锁
s.m.Lock()
if l2, ok := s.locks[key]; ok {
s.m.Unlock()
l2.rw.Lock()
fmt.Println("二次检查加锁")
} else {
n := NewRWLocker()
s.locks[key] = &countLocker{rw: n, Count: 1}
s.m.Unlock()
n.Lock()
}
n := NewRWLocker()
l = &countLocker{rw: n, Count: 1}
s.locks[key] = l
}
s.m.Unlock()
l.rw.Lock()
}
func (s *SourceLocker) Unlock(key string) {
s.m.Lock()
if l, ok := s.locks[key]; ok {
atomic.AddInt32(&l.Count, -1)
l.Count--
l.rw.Unlock()
if s.distributedLocker != nil {
@@ -90,19 +72,25 @@ func (s *SourceLocker) Unlock(key string) {
}
func (s *SourceLocker) TryLock(key string) bool {
// 加读锁
s.m.RLock()
s.m.Lock()
l, ok := s.locks[key]
s.m.RUnlock()
if ok {
ret := l.rw.TryLock()
return ret
l.Count++
} else {
s.m.Lock()
n := NewRWLocker()
s.locks[key] = &countLocker{rw: n, Count: 1}
s.m.Unlock()
return n.TryLock()
l = &countLocker{rw: n, Count: 1}
s.locks[key] = l
}
s.m.Unlock()
if !l.rw.TryLock() {
s.m.Lock()
l.Count--
if l.Count == 0 {
delete(s.locks, key)
}
s.m.Unlock()
return false
}
return true
}