Table of Contents
goroutine和channel是Go语言很是棒的特点,它们提供了一种很是轻便易用的并发能力。可是当您的应用进程中有不少goroutine的时候,如何在主流程中等待全部的goroutine 退出呢?并发
1 经过Channel传递退出信号
Go的一大设计哲学就是:经过Channel共享数据,而不是经过共享内存共享数据。主流程能够经过channel向任何goroutine发送中止信号,就像下面这样:post
func run(done chan int) { for { select { case <-done: fmt.Println("exiting...") done <- 1 break default: } time.Sleep(time.Second * 1) fmt.Println("do something") } } func main() { c := make(chan int) go run(c) fmt.Println("wait") time.Sleep(time.Second * 5) c <- 1 <-c fmt.Println("main exited") }
这种方式能够实现优雅地中止goroutine,可是当goroutine特别多的时候,这种方式无论在代码美观上仍是管理上都显得笨拙不堪。spa
2 使用waitgroup
sync包中的Waitgroup结构,是Go语言为咱们提供的多个goroutine之间同步的好刀。下面是官方文档对它的描述:设计
A WaitGroup waits for a collection of goroutines to finish. The main goroutine calls Add to set the number of goroutines to wait for. Then each of the goroutines runs and calls Done when finished. At the same time, Wait can be used to block until all goroutines have finished.
一般状况下,咱们像下面这样使用waitgroup:blog
- 建立一个Waitgroup的实例,假设此处咱们叫它wg
- 在每一个goroutine启动的时候,调用wg.Add(1),这个操做能够在goroutine启动以前调用,也能够在goroutine里面调用。固然,也能够在建立n个goroutine前调用wg.Add(n)
- 当每一个goroutine完成任务后,调用wg.Done()
- 在等待全部goroutine的地方调用wg.Wait(),它在全部执行了wg.Add(1)的goroutine都调用完wg.Done()前阻塞,当全部goroutine都调用完wg.Done()以后它会返回。
那么,若是咱们的goroutine是一匹不知疲倦的牛,一直孜孜不倦地工做的话,如何在主流程中告知并等待它退出呢?像下面这样作:进程
type Service struct { // Other things ch chan bool waitGroup *sync.WaitGroup } func NewService() *Service { s := &Service{ // Init Other things ch: make(chan bool), waitGroup: &sync.WaitGroup{}, } return s } func (s *Service) Stop() { close(s.ch) s.waitGroup.Wait() } func (s *Service) Serve() { s.waitGroup.Add(1) defer s.waitGroup.Done() for { select { case <-s.ch: fmt.Println("stopping...") return default: } s.waitGroup.Add(1) go s.anotherServer() } } func (s *Service) anotherServer() { defer s.waitGroup.Done() for { select { case <-s.ch: fmt.Println("stopping...") return default: } // Do something } } func main() { service := NewService() go service.Serve() // Handle SIGINT and SIGTERM. ch := make(chan os.Signal) signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM) fmt.Println(<-ch) // Stop the service gracefully. service.Stop() }
是否是方便优雅多了?内存