在golang中对uint8的读写是原子的吗? [英] Are reads and writes for uint8 in golang atomic?

查看:255
本文介绍了在golang中对uint8的读写是原子的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与标题中一样,是否涉及原子uint8的读写操作? 逻辑上,显然必须是单个cpu指令才能读取和写入8位变量.但是无论如何,两个内核可以同时从内存中读取和写入数据,是否可以通过这种方式创建陈旧的数据?

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?

推荐答案

不能保证对本机类型的访问是在任何平台原子上进行的.这就是为什么有 sync/atomic 的原因.另请参见内存模型文档中的建议.

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)

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)

这篇关于在golang中对uint8的读写是原子的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆