Last active
June 29, 2016 15:57
-
-
Save meson10/f8d7283d2a2861a2b3ccc73a87a1157e to your computer and use it in GitHub Desktop.
Sync.Once
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"log" | |
"sync" | |
) | |
type MyStruct struct { | |
field int | |
} | |
var onceCached *MyStruct | |
func initMyStruct() MyStruct { | |
return MyStruct{field: 1} | |
} | |
var once sync.Once | |
func getIntOnce(ident int) *MyStruct { | |
log.Println("No lock", ident) | |
once.Do(func() { | |
log.Println("Initializing GetInt") | |
x := initMyStruct() | |
onceCached = &x | |
}) | |
log.Println("No lock return", ident) | |
return onceCached | |
} | |
func main() { | |
var wg sync.WaitGroup | |
for x := range []int{0, 1, 2, 3, 4, 5} { | |
wg.Add(1) | |
go func(ident int) { | |
defer wg.Done() | |
log.Println(getIntOnce(ident)) | |
}(x) | |
} | |
wg.Wait() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment