duangua5308 2016-03-21 14:13
浏览 128
已采纳

在golang中对uint8的读写是原子的吗?

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?

  • 写回答

2条回答 默认 最新

  • dsfs1233 2016-03-21 14:18
    关注

    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
    ", x, x)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 远程安装一下vasp
  • ¥15 自己做的代码上传图片时,报错
  • ¥15 Lingo线性规划模型怎么搭建
  • ¥15 关于#python#的问题,请各位专家解答!区间型正向化
  • ¥15 unity从3D升级到urp管线,打包ab包后,材质全部变紫色
  • ¥50 comsol温度场仿真无法模拟微米级激光光斑
  • ¥15 上传图片时提交的存储类型
  • ¥15 VB.NET如何绘制倾斜的椭圆
  • ¥15 arbotix没有/cmd_vel话题
  • ¥15 odoo17的分包重新供应路线如何设置?可从销售订单中实时直接触发采购订单或相关单据