forked from yudai/gotty
/
handler_atomic.go
70 lines (55 loc) · 1.2 KB
/
handler_atomic.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
66
67
68
69
70
package server
import (
"sync"
"time"
)
type counter struct {
duration time.Duration
zeroTimer *time.Timer
wg sync.WaitGroup
connections int
mutex sync.Mutex
}
func newCounter(duration time.Duration) *counter {
zeroTimer := time.NewTimer(duration)
// when duration is 0, drain the expire event here
// so that user will never get the event.
if duration == 0 {
<-zeroTimer.C
}
return &counter{
duration: duration,
zeroTimer: zeroTimer,
}
}
func (counter *counter) add(n int) int {
counter.mutex.Lock()
defer counter.mutex.Unlock()
if counter.duration > 0 {
counter.zeroTimer.Stop()
}
counter.wg.Add(n)
counter.connections += n
return counter.connections
}
func (counter *counter) done() int {
counter.mutex.Lock()
defer counter.mutex.Unlock()
counter.connections--
counter.wg.Done()
if counter.connections == 0 && counter.duration > 0 {
counter.zeroTimer.Reset(counter.duration)
}
return counter.connections
}
func (counter *counter) count() int {
counter.mutex.Lock()
defer counter.mutex.Unlock()
return counter.connections
}
func (counter *counter) wait() {
counter.wg.Wait()
}
func (counter *counter) timer() *time.Timer {
return counter.zeroTimer
}