我正在为并发go应用程序实现全局计数器。
我的用例是计数器应该在x秒后重置并写入DB。
我试过使用互斥(我可以用这个重置计数器)
此外,当我递增计数器时,我也记录了一些东西。我发现在应用程序运行大约8-9小时后,记录的行数和计数器值不匹配(互斥版本)计数器值总是较少。我仍然没有找到导致这种情况的原因。
我使用互斥锁的方式如下
func (s *Metrics) AddQps() {
s.qpsMu.Lock()
s.qps++
s.qpsMu.Unlock()
}
And the flushing of metrics is done as follows.
for {
ticker := time.NewTicker(time.Duration(interval) * time.Second)
select {
case <-ticker.C:
logger.Println("flushing metrics...")
}
}我已经实现了互斥部分的引用[How to create global counter in golang in highly concurrent system
由于上述问题,我现在尝试使用sync.atomic计数器。因为我想在x秒后刷新指标,所以我想重置计数器。
发布于 2019-05-30 16:34:13
那么使用这样的东西有什么问题呢?
func TestNameAtomic(t *testing.T) {
var i int64
atomic.AddInt64(&i, 1)
atomic.AddInt64(&i, 1)
atomic.AddInt64(&i, 1)
fmt.Println(i)
atomic.CompareAndSwapInt64(&i, i, 0)
fmt.Println(i)
}https://stackoverflow.com/questions/56355119
复制相似问题