Synchronization characteristics of Go concurrency primitives
Having defined a happened-before relationship, it is easy to lay the ground rules for the Go memory model.
Package initialization
If package A imports another package, B, then the completion of all init()
functions in package B happens before the init()
functions in package A begin.
The following program always prints B initializing
before A initializing
:
package B import "fmt" func init() { fmt.Println("B initializing") } --- package A import ( "fmt" "B" ) func init() { fmt.Println("A initializing") }
This extends to the main package as well: all packages directly or indirectly imported by the main package of a program complete their init()
functions before main()
starts. If an init()
function creates a goroutine, there is no guarantee that the goroutine will finish before main()
starts...