Best way to implement global counters for highly concurrent applications?

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

    Don't be afraid of using mutexes and locks just because you think they're "not proper Go". In your second example it's absolutely clear what's going on, and that counts for a lot. You will have to try it yourself to see how contented that mutex is, and whether adding complication will increase performance.

    If you do need increased performance, perhaps sharding is the best way to go: http://play.golang.org/p/uLirjskGeN

    The downside is that your counts will only be as up-to-date as your sharding decides. There may also be performance hits from calling time.Since() so much, but, as always, measure it first :)

提交回复
热议问题