forked from TencentBlueKing/bk-cmdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
counter.go
90 lines (75 loc) · 1.66 KB
/
counter.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package plugin
import (
"sync"
"configcenter/src/common/metric"
)
type CounterInterface interface {
metric.MetricInterf
// increase the counter with value inc, and returned the increased value.
Increase(inc float64) float64
// decrease the counter with value dec, and returned the decreased value.
Decrease(dec float64) float64
// get the current counter value.
GetCounter() float64
// set the counter with val number.
Set(val float64)
// reset the counter with 0.
Reset()
}
func NewCounterMetric(name, help string) CounterInterface {
return &CounterMetric{
name: name,
help: help,
}
}
var _ metric.MetricInterf = CounterMetric{}
type CounterMetric struct {
name string
help string
counter
}
func (cm CounterMetric) GetMeta() metric.MetricMeta {
return metric.MetricMeta{
Name: cm.name,
Help: cm.help,
}
}
func (cm CounterMetric) GetValue() (*metric.FloatOrString, error) {
return metric.FormFloatOrString(cm.counter.GetCounter())
}
func (cm CounterMetric) GetExtension() (*metric.MetricExtension, error) {
return nil, nil
}
type counter struct {
value float64
locker sync.RWMutex
}
func (c *counter) Increase(inc float64) float64 {
c.locker.Lock()
defer c.locker.Unlock()
c.value = c.value + inc
return c.value
}
func (c *counter) Decrease(dec float64) float64 {
c.locker.Lock()
defer c.locker.Unlock()
c.value = c.value - dec
return c.value
}
func (c counter) GetCounter() float64 {
c.locker.RLock()
defer c.locker.RUnlock()
return c.value
}
func (c *counter) Set(val float64) {
c.locker.Lock()
defer c.locker.Unlock()
c.value = val
return
}
func (c *counter) Reset() {
c.locker.Lock()
defer c.locker.Unlock()
c.value = 0
return
}