-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmutex_slqueue.go
57 lines (46 loc) · 1.12 KB
/
mutex_slqueue.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
package slqueue
import (
"runtime"
"sync"
)
type MutexQueue struct {
mu sync.Mutex
capacity int
queue []int
}
func NewMutexQueue(capacity int) *MutexQueue {
return &MutexQueue{
capacity: capacity,
queue: []int{},
}
}
func (s *MutexQueue) Push(i int) {
// acquire lock first to read len(s.queue) and write to the queue atomically
s.mu.Lock()
for len(s.queue) == s.capacity {
// This unlock is necessary to prevent deadlock.
// One possible deadlock scenario (which can heppen when these Unlock/Lock doesn't exist in the loop):
// 1. call Push() when the queue is full
// 2. enter the loop holding the mutex lock
// 3. another goroutine calls Pop() <- deadlock!
s.mu.Unlock()
// yield the processor allowing other goroutines to run
runtime.Gosched()
// Then, acquire lock again to restart the loop, before entering the critical section
s.mu.Lock()
}
s.queue = append(s.queue, i)
s.mu.Unlock()
}
func (s *MutexQueue) Pop() int {
s.mu.Lock()
for len(s.queue) == 0 {
s.mu.Unlock()
runtime.Gosched()
s.mu.Lock()
}
ret := s.queue[0]
s.queue = s.queue[1:]
s.mu.Unlock()
return ret
}