Created
May 7, 2014 06:22
-
-
Save hayajo/a7c6f7aad8cd4ceaa79e to your computer and use it in GitHub Desktop.
golangでsingleton
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 "sync" | |
type MySingleton struct { | |
} | |
var ch = make(chan bool, 1) | |
var s *MySingleton = nil | |
func GetMySingleton() *MySingleton { | |
ch <- true | |
defer func() { | |
<-ch | |
}() | |
if s == nil { | |
s = new(MySingleton) | |
} | |
return s | |
} | |
func main() { | |
var wg sync.WaitGroup | |
for i := 0; i < 10; i++ { | |
wg.Add(1) | |
go func() { | |
o := GetMySingleton() | |
wg.Done() | |
}() | |
} | |
wg.Wait() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
goroutineを気にするとこんな感じなのかな。
sync.Onceつかう実装だとnilになった場合に再生成できないのでチャネル使った実装にしてみました。