-
Notifications
You must be signed in to change notification settings - Fork 385
/
Copy pathmanager.go
82 lines (66 loc) · 1.63 KB
/
manager.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package link
import "sync"
const sessionMapNum = 32
type Manager struct {
sessionMaps [sessionMapNum]sessionMap
disposeOnce sync.Once
disposeWait sync.WaitGroup
}
type sessionMap struct {
sync.RWMutex
sessions map[uint64]*Session
disposed bool
}
func NewManager() *Manager {
manager := &Manager{}
for i := 0; i < len(manager.sessionMaps); i++ {
manager.sessionMaps[i].sessions = make(map[uint64]*Session)
}
return manager
}
func (manager *Manager) Dispose() {
manager.disposeOnce.Do(func() {
for i := 0; i < sessionMapNum; i++ {
smap := &manager.sessionMaps[i]
smap.Lock()
smap.disposed = true
for _, session := range smap.sessions {
session.Close()
}
smap.Unlock()
}
manager.disposeWait.Wait()
})
}
func (manager *Manager) NewSession(codec Codec, sendChanSize int) *Session {
session := newSession(manager, codec, sendChanSize)
manager.putSession(session)
return session
}
func (manager *Manager) GetSession(sessionID uint64) *Session {
smap := &manager.sessionMaps[sessionID%sessionMapNum]
smap.RLock()
defer smap.RUnlock()
session, _ := smap.sessions[sessionID]
return session
}
func (manager *Manager) putSession(session *Session) {
smap := &manager.sessionMaps[session.id%sessionMapNum]
smap.Lock()
defer smap.Unlock()
if smap.disposed {
session.Close()
return
}
smap.sessions[session.id] = session
manager.disposeWait.Add(1)
}
func (manager *Manager) delSession(session *Session) {
smap := &manager.sessionMaps[session.id%sessionMapNum]
smap.Lock()
defer smap.Unlock()
if _, ok := smap.sessions[session.id]; ok {
delete(smap.sessions, session.id)
manager.disposeWait.Done()
}
}