Is there a difference in Go between a counter using atomic operations and one using a mutex?

后端 未结 3 1457
南方客
南方客 2021-02-07 11:26

I have seen some discussion lately about whether there is a difference between a counter implemented using atomic increment/load, and one using a mutex to synchronise increment/

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-07 11:54

    There is no difference in behavior. There is a difference in performance.

    Mutexes are slow, due to the setup and teardown, and due to the fact that they block other goroutines for the duration of the lock.

    Atomic operations are fast because they use an atomic CPU instruction, rather than relying on external locks to.

    Therefore, whenever it is feasible, atomic operations should be preferred.

提交回复
热议问题