Gracefully exit Goroutines in the Go language

Source: Internet
Author: User
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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.