This is a creation in Article, where the information may have evolved or changed.
Gracefully exiting Goroutines in the go language, you usually need to do the following 3 points:
1. Send a notice to each goroutines to withdraw it, such as shutdown.
2. Wait for each goroutines to exit, such as: Sync. Waitgroup.
3. Ensure that data is not lost before exiting the Goroutine (1. Stop production data. 2. Turn off data channel messages. 3. The consumer Goroutine checks to determine whether the data channel messages is valid and, if not, exits. )
PackageMainImport( "FMT""Sync""OS""Os/signal""Syscall")funcConsumer(Messages <-Chanint, shutdown <-Chanint, WG *sync. Waitgroup) {deferWG. Done() for{ Select{ Casemessage, OK: = <-messages://do something. ifOK {fmt.Println(Message)}Else{ //no data, exit. FMT.Println("no data, exit.") return } Case_ = <-shutdown://we ' re done! //shutdown Now, messages buffered channel data is lost. FMT.Println("All done!") return } }}funcMain() { //signals handle. Shutdown: = Make(Chanint) SIGs: = Make(ChanOS. Signal, 1) signal.Notify(SIGs, Syscall.SIGINT, Syscall.SIGTERM) go func() {sig: = <-sigs fmt.Println(SIG)//shutdown Now, messages buffered channel data is lost.//close (Shutdown)/*or*/shutdown <-0 } () Messages: = Make(Chanint, -WG: = &sync. waitgroup{} WG.ADD(1) GoConsumer(Messages, shutdown, WG) forI: =0; I <Ten; i++ {messages <-i}Close(Messages)//flush Messages channel, no data loss. FMT.Println("wait!") WG.Wait()}
Note: This article is only my personal notes, if there are errors and omissions, please correct me, study together, my e-mail: htyu_0203_39@sina.com