douzhaochan6468 2015-07-02 19:48
浏览 29
已采纳

是否可以确保sync.Once.Do跨goroutine可见?

The example here implies that sync.Once.Do guarantees visibility across goroutines for the string var a. Is that also true if for example the function f() called by sync.Once.Do initializes multiple fields of a struct instance? Will all the fields of the struct instance be visible to other goroutines without any additional synchronization?

  • 写回答

1条回答 默认 最新

  • duanfan9859 2015-07-02 21:07
    关注

    Let's break down the example:

    The variable a is set before the function setup() returns because reads and writes within a single goroutine must behave as if they executed in the order specified by the program [1].

    The single call to setup() from once.Do() happens before any call of once.Do() returns [2].

    Therefore, the variable a is set before any call to once.Do() returns. No further synchronization is required to establish this before relationship.

    The question asks about struct fields, not a single variable as in the example. As far as the memory model is concerned, struct fields are variables. All of the logic that applies to the variable in the example applies to fields in a struct.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!