dtxa49711 2019-05-29 07:23
浏览 256

有没有一种方法可以重置使用atomic.AddUint64递增的计数器?

I am implementing global counters for a concurrent go application.

My use case is that the counter should be reset after x seconds and written to DB.

I have tried using mutex (I am able to reset counter using this)

Also when I increment the counter I also log something. I have found that after the application runs for about 8-9 hours the number of lines logged and the counter value do not match (mutex version) Counter values is always less. I have still not found the cause for this.

I am using mutex in the following manner

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...")
    }
}

I had implemented the mutex part referencing [How to create global counter in golang in highly concurrent system

Due to the above mentioned problem I am now trying counters using sync.atomic. As I want the metric to be flushed after x seconds I wanted to reset the counter.

  • 写回答

1条回答 默认 最新

  • dousha2020 2019-05-30 08:34
    关注

    So what is the problem to use something like this?

    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)
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 C#调用python代码(python带有库)
  • ¥15 矩阵加法的规则是两个矩阵中对应位置的数的绝对值进行加和
  • ¥15 活动选择题。最多可以参加几个项目?
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)
  • ¥20 怎么在stm32门禁成品上增加查询记录功能
  • ¥15 Source insight编写代码后使用CCS5.2版本import之后,代码跳到注释行里面