aboutsummaryrefslogtreecommitdiff
path: root/internal/mutex.go
blob: 3d36cdac95b3a4c2773eea35ca341df35bfb4617 (plain)
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
package internal

import "sync"

type MutexByRoom struct {
	mu       *sync.Mutex // protects the map
	roomToMu map[string]*sync.Mutex
}

func NewMutexByRoom() *MutexByRoom {
	return &MutexByRoom{
		mu:       &sync.Mutex{},
		roomToMu: make(map[string]*sync.Mutex),
	}
}

func (m *MutexByRoom) Lock(roomID string) {
	m.mu.Lock()
	roomMu := m.roomToMu[roomID]
	if roomMu == nil {
		roomMu = &sync.Mutex{}
	}
	m.roomToMu[roomID] = roomMu
	m.mu.Unlock()
	// don't lock inside m.mu else we can deadlock
	roomMu.Lock()
}

func (m *MutexByRoom) Unlock(roomID string) {
	m.mu.Lock()
	roomMu := m.roomToMu[roomID]
	if roomMu == nil {
		panic("MutexByRoom: Unlock before Lock")
	}
	m.mu.Unlock()

	roomMu.Unlock()
}