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?
问问题
6100 次
2 回答
9
不能保证对本机类型的访问在任何平台上都是原子的。这就是为什么存在sync/atomic
. 另请参阅内存模型文档中的建议。
以原子方式设置值的通用方式示例(Play)
var ax atomic.Value // may be globally accessible
x := uint8(5)
// set atomically
ax.Store(x)
x = ax.Load().(uint8)
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)
于 2016-03-21T14:18:40.573 回答
9
不,如果你想要原子操作,你可以使用这个sync/atomic
包。
如果您的意思是“即使我忽略 Go内存模型,8 位操作也会是原子的吗?”,那么答案仍然是,这取决于可能不是。
如果硬件保证读/写操作的原子性,那么它可能是原子的。但这仍然不能保证缓存的一致性,或者重新排序操作的编译器优化。您需要以某种方式序列化操作,使用 Go 在“atomic”包中提供的原语,并使用“sync”包和通道在 goroutine 之间进行协调。
于 2016-03-21T14:17:31.857 回答