When you use Golang for concurrent programming, when you start a new goroutine asynchronously, the main goroutine does not know if the other goroutine is finished, and once the main goroutine exits, all the goroutine exits. Therefore, you need to control the main goroutine exit time, there are the following methods:
(1) time. Sleep ()
More brutal, not reliable, is to let the main goroutine more run for a while, the actual is not sure whether the other goroutine is run over.
(2) Using channel communication
In the main goroutine has been blocked waiting for an exit signal, after the other Goroutine completed the task to send a signal to the main, the main process received this signal to exit
E: = Make (chan bool)
Go func () {
Fmt. Println ("Hello")
E <-True
}()
<-e
(3) Use sync. Waitgroup
Waitgroup, it can wait until all goroutine execution completes, and blocks the execution of the main thread until all goroutine (the concurrent execution of the Golang) is completed.
var WG Sync. Waitgroup
func main () {
WG. ADD (1)
go func () {
FMT. Println ("Hello")
WG. Done ()//Complete
} ()
WG. Wait ()
}