1 Star 0 Fork 0

李童/training-operator

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
counter.go 1.06 KB
一键复制 编辑 原始数据 按行查看 历史
package util
import (
"fmt"
"sync"
)
type Counter struct {
lock sync.Mutex
data map[string]int
}
func NewCounter() *Counter {
return &Counter{
lock: sync.Mutex{},
data: map[string]int{},
}
}
func (c *Counter) Inc(key string) {
c.lock.Lock()
defer c.lock.Unlock()
v, ok := c.data[key]
if ok {
c.data[key] = v + 1
return
}
c.data[key] = 0
}
func (c *Counter) DeleteKey(key string) {
c.lock.Lock()
defer c.lock.Lock()
delete(c.data, key)
}
func (c *Counter) Counts(key string) (int, error) {
c.lock.Lock()
defer c.lock.Unlock()
v, ok := c.data[key]
if !ok {
return 0, fmt.Errorf("cannot get key %s", key)
}
var err error = nil
if v < 0 {
err = fmt.Errorf("count %s:%d is negative", key, v)
}
return v, err
}
func (c *Counter) Dec(key string) error {
c.lock.Lock()
defer c.lock.Unlock()
v, ok := c.data[key]
if ok {
if v > 1 {
c.data[key] = v - 1
return nil
}
if v == 1 {
c.DeleteKey(key)
return nil
}
return fmt.Errorf("cannot minus one: key %s has value %d", key, v)
}
return fmt.Errorf("cannot find key %s", key)
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/vak80/training-operator.git
git@gitee.com:vak80/training-operator.git
vak80
training-operator
training-operator
v1.7.0-fix

搜索帮助