-
Notifications
You must be signed in to change notification settings - Fork 10
/
sync.go
65 lines (55 loc) · 1.14 KB
/
sync.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
package lobby
import (
"sync"
db "github.com/TF2Stadium/Helen/database"
)
var (
mu = new(sync.RWMutex)
lobbyLocks = make(map[uint]*sync.Mutex)
)
//Lock aquires the lock for the given lobby.
//Be careful while using Lock outside of models,
//improper usage could result in deadlocks
func (lobby *Lobby) Lock() {
mu.RLock()
lock, ok := lobbyLocks[lobby.ID]
mu.RUnlock()
if ok {
lock.Lock()
}
}
//Unlock releases the lock for the given lobby
func (lobby *Lobby) Unlock() {
mu.RLock()
lock, ok := lobbyLocks[lobby.ID]
mu.RUnlock()
if ok {
lock.Unlock()
}
}
//CreateLock creates a lock for lobby
func (lobby *Lobby) CreateLock() {
mu.Lock()
lobbyLocks[lobby.ID] = new(sync.Mutex)
mu.Unlock()
}
func (lobby *Lobby) deleteLock() {
mu.Lock()
lock, ok := lobbyLocks[lobby.ID]
if ok {
lock.Lock()
delete(lobbyLocks, lobby.ID)
lock.Unlock()
}
mu.Unlock()
}
//CreateLocks creates locks for all lobbies that haven't ended yet
func CreateLocks() {
mu.Lock()
defer mu.Unlock()
var ids []uint
db.DB.Model(&Lobby{}).Where("state <> ?", Ended).Pluck("id", &ids)
for _, id := range ids {
lobbyLocks[id] = new(sync.Mutex)
}
}