Best way to implement global counters for highly concurrent applications?

前端 未结 9 1193
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-23 02:07

What is the best way to implement global counters for a highly concurrent application? In my case I may have 10K-20K go routines performing \"work\", and I want to count th

9条回答
  •  感动是毒
    2020-12-23 02:43

    I implemented this with a simple map + mutex which seems to be the best way to handle this since it is the "simplest way" (which is what Go says to use to choose locks vs channels).

    package main
    
    import (
        "fmt"
        "sync"
    )
    
    type single struct {
        mu     sync.Mutex
        values map[string]int64
    }
    
    var counters = single{
        values: make(map[string]int64),
    }
    
    func (s *single) Get(key string) int64 {
        s.mu.Lock()
        defer s.mu.Unlock()
        return s.values[key]
    }
    
    func (s *single) Incr(key string) int64 {
        s.mu.Lock()
        defer s.mu.Unlock()
        s.values[key]++
        return s.values[key]
    }
    
    func main() {
        fmt.Println(counters.Incr("bar"))
        fmt.Println(counters.Incr("bar"))
        fmt.Println(counters.Incr("bar"))
        fmt.Println(counters.Get("foo"))
        fmt.Println(counters.Get("bar"))
    
    }
    

    You can run the code on https://play.golang.org/p/9bDMDLFBAY. I made a simple packaged version on gist.github.com

提交回复
热议问题