Files
zogo/counter/README.md
T
4566704 75f0b78d52 feat(counter): go-hua/single 迁入并更名 counter(键值计数器)
- 原包名 single 名不达意,实为 string→int64 并发计数器;类型 Single→Counter,
  方法签名不变(Init/Get/Incr/Set),附测试、例程与 README
2026-09-20 12:20:51 +08:00

39 lines
856 B
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# counter
线程安全的 `string → int64` 键值计数器,适合并发计数场景(按 key 累加/读取/覆盖)。
> 迁移自 go-hua/single 并更名:包 `single` → `counter`,类型 `Single` → `Counter`,
> 方法签名不变(Init/Get/Incr/Set)。
## 用法
```go
import (
"sync"
"git.zeroonesoft.cn/golib/zogo/counter"
)
var c counter.Counter
c.Init()
// 并发安全累加
var wg sync.WaitGroup
for i := 0; i < 100; i++ {
wg.Add(1)
go func() { defer wg.Done(); c.Incr("pv", 1) }()
}
wg.Wait()
c.Get("pv") // 100
// Set 覆盖并返回旧值
old := c.Set("pv", 0)
```
完整可运行例程:[examples/counter/main.go](../examples/counter/main.go)
## 注意
- **使用前必须 Init**,未初始化直接 `Incr/Set` 会 panic(nil map 写入)。
- 单实例内部持锁;跨实例无共享状态。