在go語言中優雅退出goroutines

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

在go語言中優雅退出goroutines,通常需要做以下3點:

1. 向各個goroutines發通知,令其退出,如shutdown.

2. 等待各個goroutines都退出,如: sync.WaitGroup.

3. 在退出goroutine之前,確保資料不丟失(1.停止生產資料。2.關閉資料channel messages. 3. 消費者goroutine檢查判斷資料channel messages是否有效,若無效,則退出。)


package mainimport (       "fmt"       "sync"       "os"       "os/signal"       "syscall")func consumer(messages <- chan int, shutdown <- chan int, wg *sync.WaitGroup) {       defer wg.Done()       for {              select {              case message, ok := <- messages:              //do something.              if ok {                     fmt.Println(message)              } else {                     //no data , exit.                     fmt.Println("no data, exit.")                     return              }              case _ = <- shutdown:              //we `re done!              //shutdown now , messages buffered channel data may be lost.                     fmt.Println("all done!")                     return              }       }}func main() {       //signals handle.       shutdown := make(chan int)       sigs := make(chan os.Signal, 1)       signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)       go func() {              sig := <- sigs              fmt.Println(sig)              //shutdown now , messages buffered channel data may be lost.              //close(shutdown)              /*or*/shutdown <- 0       } ()       messages := make(chan int, 16)       wg := &sync.WaitGroup{}       wg.Add(1)       go consumer(messages, shutdown, wg)       for i := 0; i < 10; i++ {              messages <- i       }       close(messages) //flush messages channel , no data loss.       fmt.Println("wait!")       wg.Wait()}

注意: 此文章只是我個人筆記, 如有錯漏,請一定指正, 共同學習, 我的郵箱: htyu_0203_39@sina.com

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.