是否可以确保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?
示例此处表示sync.Once.Do保证了字符串var a在goroutine中的可见性。 如果例如由sync.Once.Do调用的函数f()初始化一个结构实例的多个字段,这是否也是正确的? p> div>是否可以将struct实例的所有字段对其他goroutine可见? p> div>
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.