Best way to implement global counters for highly concurrent applications?

前端 未结 9 1192
佛祖请我去吃肉
佛祖请我去吃肉 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:46

    If your work counter types are not dynamic, i.e. you can write them all out upfront, I don't think you'll get much simpler or faster than this.

    No mutex, no channel, no map. Just a statically sized array and an enum.

    type WorkType int
    
    const (
        WorkType1 WorkType = iota
        WorkType2
        WorkType3
        WorkType4
        NumWorkTypes
    )
    
    var workCounter [NumWorkTypes]int64
    
    func updateWorkCount(workType WorkType, delta int) {
        atomic.AddInt64(&workCounter[workType], int64(delta))
    }
    

    Usage like so:

    updateWorkCount(WorkType1, 1)
    

    If you need to sometimes work with work types as strings for display purposes, you can always generate code with a tool like stringer

提交回复
热议问题