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 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分