usage golang atomic LoadInt32/StoreInt32 (64)

后端 未结 1 647
长情又很酷
长情又很酷 2021-01-03 04:45

Can anybody show the example where usage of such atomic operations needed. I don\'t understand a differenece between

import \"sync/atomic\"

...
var sharedA         


        
相关标签:
1条回答
  • 2021-01-03 05:24

    It's not documented in the package at all, but normally atomic loads and stores of normal values are there not for atomicity because the CPU operations are already atomic, but for ordering. The language specification or CPU instruction documentation gives you certain guarantees about in which order one CPU stores will be seen by another CPU if you use the atomic operations. Most modern CPUs have no such guarantees if you don't use the proper (expensive) instructions for it.

    So in your example (I assume, since the package isn't documented), if the shared variables have been written by a goroutine first to sharedA, then sharedB, when reading then without atomic operations you might see the changed value of sharedB and still the old value of sharedA. It's different on different CPU families if the stores or loads need to perform extra magic to get the ordering right, so usually languages make you use atomic functions for both stores and loads and then the compiler/library knows what your actual CPU needs.

    Of course, the package doesn't document any of this, so in practice there is no difference because we don't know what the package actually guarantees. So for all practical purposes it's useless.

    0 讨论(0)
提交回复
热议问题