优雅主动停止goroutine - Go语言中文社区

优雅主动停止goroutine


一、for-rang从channel上接收值,直到channel关闭

func goExit1() {
	var wg sync.WaitGroup
	inCh := make(chan int)
	wg.Add(1)
	go func(in <-chan int, wg *sync.WaitGroup) {
		defer wg.Done()
		// Using for-range to exit goroutine
		// range has the ability to detect the close/end of a channel
		for 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退出信号

func goExit2() {
	var wg sync.WaitGroup
	inCh := make(chan int)
	quitCh := make(chan int)
	wg.Add(1)
	go func(in <-chan int, quit <-chan int, 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 <- 1
	close(inCh)
	close(quitCh)
	wg.Wait()
	fmt.Println("结束")
}

三、for-selec监听多个channel退出信号

func goExit3() {
	var wg sync.WaitGroup
	inCh := make(chan int)
	quitCh1 := make(chan int)
	quitCh2 := make(chan int)
	wg.Add(1)
	go func(wg *sync.WaitGroup, in, quit, quit2 <-chan int) {
		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 <- 1
	close(inCh)
	close(quitCh1)
	close(quitCh2)
	wg.Wait()
	fmt.Println("结束")
}

四、使用context包退出协程

func context2() {
	var wg sync.WaitGroup
	// 3*time.Second  表示设置3秒超时,超时后子程序会自动退出。
	//ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
	ctx, cancel := context.WithCancel(context.Background())
	wg.Add(1)
	go func(ctx context.Context, wg *sync.WaitGroup) {
		defer wg.Done()
		for {
			select {
			case <-ctx.Done():
				fmt.Println("ctx.Done()通道退出")
				return
			default:
				fmt.Println("执行默认分支,并休眠1秒")
				time.Sleep(time.Second * 1)
			}
		}
	}(ctx, &wg)

	time.Sleep(time.Second * 5)
	cancel()
	wg.Wait()
	fmt.Println("主线程结束")
}
版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/qq_38776443/article/details/128117840
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2023-01-05 03:40:08
  • 阅读 ( 340 )
  • 分类:Go

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢