s********k 发帖数: 6180 | 1 比如需要初始化client,保证thread safe singleton, 看到很多资料都用once.Do(
func(){})这样来做,但是同事看到如果在package用init,If multiple packages
import a package P, P will be initialized only once. 这里的init是不是也是
thread safe? |
d****n 发帖数: 1637 | 2 not thread safe.
init(s) was called by the order of dependency tree.
if in same folder level, called alphabetical order.
e.g. if two init functions have concurrent writings to same map, then god
bless you.
BTW: you can avoid such thing happen by using sync.Mutex or concurrent map
in golang 1.9+ |
d****n 发帖数: 1637 | 3 you can check it by using golang's race detector.
$ go test -race mypkg // to test the package
$ go run -race mysrc.go // to run the source file
$ go build -race mycmd // to build the command
$ go install -race mypkg // to install the package |
s********k 发帖数: 6180 | 4 Thanks, 用sync.Once也可以吧
【在 d****n 的大作中提到】 : you can check it by using golang's race detector. : $ go test -race mypkg // to test the package : $ go run -race mysrc.go // to run the source file : $ go build -race mycmd // to build the command : $ go install -race mypkg // to install the package
|