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 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿