Best way to implement global counters for highly concurrent applications?

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

    Don't use sync/atomic - from the linked page

    Package atomic provides low-level atomic memory primitives useful for implementing synchronization algorithms. These functions require great care to be used correctly. Except for special, low-level applications, synchronization is better done with channels or the facilities of the sync package

    Last time I had to do this I benchmarked something which looked like your second example with a mutex and something which looked like your third example with a channel. The channels code won when things got really busy, but make sure you make the channel buffer big.

提交回复
热议问题