-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathwindow.go
64 lines (55 loc) · 968 Bytes
/
window.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
// Copyright 2015 The GoTor Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"sync"
)
type Window struct {
cond *sync.Cond
window int
}
func NewWindow(window int) *Window {
return &Window{
cond: sync.NewCond(&sync.Mutex{}),
window: window,
}
}
func (w *Window) Abort() {
w.cond.Broadcast()
}
func (w *Window) Refill(count int) {
w.cond.L.Lock()
w.window += count
w.cond.Broadcast()
w.cond.L.Unlock()
}
func (w *Window) Take() bool {
w.cond.L.Lock()
if w.window <= 0 {
w.cond.Wait()
}
st := false
if w.window > 0 {
st = true
w.window--
}
w.cond.L.Unlock()
return st
}
func (w *Window) TryTake() bool {
w.cond.L.Lock()
if w.window > 0 {
w.window--
w.cond.L.Unlock()
return true
}
w.cond.L.Unlock()
return false
}
func (w *Window) GetLevel() int {
w.cond.L.Lock()
l := w.window
w.cond.L.Unlock()
return l
}