1 Star 0 Fork 0

magicianlyx / GoLog

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
counter.go 649 Bytes
一键复制 编辑 原始数据 按行查看 历史
magicianlyx 提交于 2022-01-24 17:45 . -
package pool
import "sync"
// 计数器(线程安全)
type Counter struct {
x int64
max int64
l sync.RWMutex
}
func NewCounter() *Counter {
return &Counter{
x: 0,
max: 0,
l: sync.RWMutex{},
}
}
// 自增
func (c *Counter) Inc() int64 {
c.l.Lock()
defer c.l.Unlock()
c.x += 1
if c.max < c.x {
c.max = c.x
}
return c.x
}
// 自减
func (c *Counter) Dec() int64 {
c.l.Lock()
defer c.l.Unlock()
c.x -= 1
return c.x
}
// 获取峰值
func (c *Counter) GetMax() int64 {
c.l.RLock()
defer c.l.RUnlock()
return c.max
}
// 获取值
func (c *Counter) Get() int64 {
c.l.RLock()
defer c.l.RUnlock()
return c.x
}
Go
1
https://gitee.com/magicianlyx/GoLog.git
git@gitee.com:magicianlyx/GoLog.git
magicianlyx
GoLog
GoLog
20c45f9b998d

搜索帮助

53164aa7 5694891 3bd8fe86 5694891