Are reads and writes for uint8 in golang atomic?

折月煮酒 提交于 2019-12-10 15:38:46

问题


As in the title, are read and write operations regarding uint8, atomic? Logically it must be a single cpu instruction obviously to read and write for a 8 bit variable. But in any case, two cores could simultaneously read and write from the memory, is it possible to create a stale data this way?


回答1:


There's no guarantee that the access on native types are on any platform atomic. This is why there is sync/atomic. See also the advice in the memory model documentation.

Example for generic way of atomically setting a value (Play)

var ax atomic.Value // may be globally accessible

x := uint8(5)

// set atomically
ax.Store(x)

x = ax.Load().(uint8)

Probably more efficient solution for uint8 (Play):

var ax int64 // may be globally accessible

x := uint8(5)

atomic.StoreInt64(&ax, 10)

x = uint8(atomic.LoadInt64(&ax))

fmt.Printf("%T %v\n", x, x)



回答2:


No. If you want atomic operations, you can use the sync/atomic package.

If you mean "would 8bit operations be atomic even if I ignore the Go memory model?", then the answer is still, it depends probably not.

If the hardware guarantees atomicity of read/write operations, then it might be atomic. But that still doesn't guarantee cache coherence, or compiler optimizations from reordering operations. You need to serialize the operations somehow, with the primitives Go provides in the "atomic" package, and using the "sync" package and channels to coordinate between goroutines.



来源:https://stackoverflow.com/questions/36133364/are-reads-and-writes-for-uint8-in-golang-atomic

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!