funcgoExit1(){var wg sync.WaitGroup
inCh :=make(chanint)
wg.Add(1)gofunc(in <-chanint, wg *sync.WaitGroup){defer wg.Done()// Using for-range to exit goroutine// range has the ability to detect the close/end of a channelfor x :=range in {
time.Sleep(time.Second *1)
fmt.Printf("Process %d %d\n", x, runtime.NumGoroutine())}}(inCh,&wg)for i :=0; i <10; i++{
inCh <- i
}close(inCh)
wg.Wait()
fmt.Println("结束")}
二、for-selec监听channel退出信号
funcgoExit2(){var wg sync.WaitGroup
inCh :=make(chanint)
quitCh :=make(chanint)
wg.Add(1)gofunc(in <-chanint, quit <-chanint, wg *sync.WaitGroup){defer wg.Done()for{select{case x :=<-in:
time.Sleep(time.Second *2)
fmt.Printf("Process %d %d\n", x, runtime.NumGoroutine())case<-quit:
time.Sleep(time.Second *2)
fmt.Println("收到退出信息")return}}}(inCh, quitCh,&wg)for i :=0; i <10; i++{
inCh <- i
}
quitCh <-1close(inCh)close(quitCh)
wg.Wait()
fmt.Println("结束")}
三、for-selec监听多个channel退出信号
funcgoExit3(){var wg sync.WaitGroup
inCh :=make(chanint)
quitCh1 :=make(chanint)
quitCh2 :=make(chanint)
wg.Add(1)gofunc(wg *sync.WaitGroup, in, quit, quit2 <-chanint){defer wg.Done()for{select{case x :=<-in:
time.Sleep(time.Second *2)
fmt.Printf("Process %d %d\n", x, runtime.NumGoroutine())case_, ok :=<-quit:if!ok {
fmt.Println("收到退出信号")
quit =nil}case_, ok :=<-quit2:if!ok {
fmt.Println("收到退出信号")
quit2 =nil}}if quit ==nil&& quit2 ==nil{return}}}(&wg, inCh, quitCh1, quitCh2)for i :=0; i <10; i++{
inCh <- i
}
quitCh1 <-1
quitCh2 <-1close(inCh)close(quitCh1)close(quitCh2)
wg.Wait()
fmt.Println("结束")}