Skip to content

Commit

Permalink
tmp: add write lock
Browse files Browse the repository at this point in the history
  • Loading branch information
AsterDY committed Jul 30, 2024
1 parent f2a2c21 commit 7c59233
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 17 deletions.
4 changes: 2 additions & 2 deletions api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -376,15 +376,15 @@ func TestSessionManager_GC(t *testing.T) {
}
for _, shard := range manager.shards {
shard.lock.Lock()
l := len(*shard.m)
l := len(shard.m)
shard.lock.Unlock()
require.Equal(t, N/sd, l)
}
time.Sleep(inter + inter>>1)
sum := 0
for _, shard := range manager.shards {
shard.lock.Lock()
l := len(*shard.m)
l := len(shard.m)
shard.lock.Unlock()
sum += l
}
Expand Down
27 changes: 12 additions & 15 deletions manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ import (
"sync"
"sync/atomic"
"time"
"unsafe"
)

// ManagerOptions for SessionManager
Expand All @@ -40,7 +39,7 @@ type ManagerOptions struct {

type shard struct {
lock sync.RWMutex
m *map[SessionID]Session
m map[SessionID]Session
}

// SessionManager maintain and manage sessions
Expand All @@ -55,8 +54,7 @@ var defaultShardCap = 10

func newShard() *shard {
ret := new(shard)
m := make(map[SessionID]Session, defaultShardCap)
ret.m = &m
ret.m = make(map[SessionID]Session, defaultShardCap)
return ret
}

Expand Down Expand Up @@ -92,25 +90,23 @@ type SessionID uint64
func (s *shard) Load(id SessionID) (Session, bool) {
s.lock.RLock()

p := atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(&s.m)))
m := *(*map[SessionID]Session)(unsafe.Pointer(p))
// p := atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(&s.m)))
// m := *(*map[SessionID]Session)(unsafe.Pointer(p))

session, ok := m[id]
session, ok := s.m[id]
s.lock.RUnlock()
return session, ok
}

func (s *shard) Store(id SessionID, se Session) {
s.lock.Lock()
m := *s.m
m[id] = se
s.m[id] = se
s.lock.Unlock()
}

func (s *shard) Delete(id SessionID) {
s.lock.Lock()
m := *s.m
delete(m, id)
delete(s.m, id)
s.lock.Unlock()
}

Expand Down Expand Up @@ -170,17 +166,18 @@ func (self SessionManager) GC() {
}

for _, shard := range self.shards {
shard.lock.RLock()
n := *shard.m
shard.lock.Lock()
n := shard.m
m := make(map[SessionID]Session, len(n))
for id, s := range n {
// Warning: may panic here?
if s.IsValid() {
m[id] = s
}
}
atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(&shard.m)), unsafe.Pointer(&m))
shard.lock.RUnlock()
// atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(&shard.m)), unsafe.Pointer(&m))
shard.m = m
shard.lock.Unlock()
}

atomic.StoreUint32(&self.inGC, 0)
Expand Down

0 comments on commit 7c59233

Please sign in to comment.