once 只执行一次代码,竞争条件下也是安全的;
func main() {
var once = Once {
func() {
fmt.Println("Only once")
},
0,
sync.Mutex{},
}
goroutine(&once)
goroutine(&once)
time.Sleep(1) // wait for goroutines to complete
}func goroutine(once *Once) {
once.Do()
}