Skip to content

Instantly share code, notes, and snippets.

@meson10
Last active June 29, 2016 15:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save meson10/ce875932562fce333d69f68c7f7cd18f to your computer and use it in GitHub Desktop.
Save meson10/ce875932562fce333d69f68c7f7cd18f to your computer and use it in GitHub Desktop.
Sync with Lock
package main
import (
"log"
"sync"
)
type MyStruct struct {
field int
}
var lockCached = struct {
sync.RWMutex
val *MyStruct
}{}
func initMyStruct() MyStruct {
return MyStruct{field: 1}
}
func getIntLock(ident int) *MyStruct {
lockCached.Lock()
log.Println("lock", ident)
if lockCached.val == nil {
log.Println("Initializing GetInt")
x := initMyStruct()
lockCached.val = &x
}
lockCached.Unlock()
log.Println("lock freed", ident)
return lockCached.val
}
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(getIntLock(ident))
}(x)
}
wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment