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.