优雅主动停止goroutine

本文介绍了在 Go 语言中如何优雅地退出协程的四种方法:通过 for-range 检测 channel 关闭、使用 for-select 监听退出信号、监听多个 channel 退出以及借助 context 包。每种方法都展示了如何在接收到退出信号后停止协程执行,并确保资源的正确释放。
摘要由CSDN通过智能技术生成

一、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("主线程结束")
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值