blob: 941dc9f2adb0d38610295a997293f358ddf30244 (
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
// Copyright 2015 syzkaller project authors. All rights reserved.
// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.
package ipc
import (
"sync"
)
// Gate limits concurrency level and window to the given value.
// Limitation of concurrency window means that if a very old activity is still
// running it will not let new activities to start even if concurrency level is low.
type Gate struct {
cv *sync.Cond
busy []bool
pos int
}
func NewGate(c int) *Gate {
return &Gate{
cv: sync.NewCond(new(sync.Mutex)),
busy: make([]bool, c),
}
}
func (g *Gate) Enter() int {
g.cv.L.Lock()
for g.busy[g.pos] {
g.cv.Wait()
}
idx := g.pos
g.pos++
if g.pos >= len(g.busy) {
g.pos = 0
}
g.busy[idx] = true
g.cv.L.Unlock()
return idx
}
func (g *Gate) Leave(idx int, f func()) {
g.cv.L.Lock()
if !g.busy[idx] {
panic("broken gate")
}
if f != nil {
f()
}
g.busy[idx] = false
if idx == g.pos {
g.cv.Broadcast()
}
g.cv.L.Unlock()
}
|