11. Golang如何正确退出Goroutine

Go语言中,Goroutine是一种轻量级线程,它的退出机制对于并发编程至关重要。

函数或方法执行完毕

最常见的Goroutine退出方式是函数或方法执行完毕。当Goroutine中的函数或方法执行完毕时,该Goroutine会自动退出。

package main
import (
	"fmt"
	"time"
)
func main() {
	go func() {
		// Goroutine 中的函数执行完毕后自动退出
		fmt.Println("Goroutine execution complete")
	}()
	// 主 Goroutine 继续执行其他任务
	time.Sleep(time.Second)
	fmt.Println("Main Goroutine execution complete")
}

在上面的示例中,我们创建了一个匿名的Goroutine,在其中打印一条消息,然后Goroutine执行完毕并自动退出。主Goroutine继续执行其他任务。

子协程返回

Goroutine中,我们可以使用return语句显式地退出。当执行到return语句时,该Goroutine将会终止并返回,注:协程是没有返回值的,如果要返回,一般是用chan,往chan中写入,外部一般用waitgroup等待go执行完成后,读取chan的结果。

package main
import (
	"fmt"
	"time"
)
func main() {
	go func() {
		// Goroutine 中使用 return 语句显式退出
		fmt.Println("Goroutine execution")
		return
	}()
	// 主 Goroutine 继续执行其他任务
	time.Sleep(time.Second)
	fmt.Println("Main Goroutine execution complete")
}

在上面的示例中,我们创建了一个匿名的Goroutine,并在其中打印一条消息,然后使用return语句显式地退出Goroutine,这里演示的是函数末尾return,实际工作中很可能是中途需要return

panic()与recover()

如果在Goroutine中发生了panic,默认情况下会终止当前程序的执行。我们可以在Goroutine中使用recover()函数来捕获并处理panic,以避免程序崩溃。

package main
import (
	"fmt"
	"time"
)
func main() {
	go func() {
		defer func() {
			if err := recover(); err != nil {
				// 在 Goroutine 中捕获并处理panic
				fmt.Println("Recovered from panic:", err)
			}
		}()
		// 引发恐慌
		panic("Goroutine panic")
	}()
	// 主 Goroutine 继续执行其他任务
	time.Sleep(time.Second)
	fmt.Println("Main Goroutine execution complete")
}

在上面的示例中,我们创建了一个匿名的Goroutine,在其中使用panic()引发panic。然后使用deferrecover()捕获并处理panic,确保程序不会崩溃。

context的取消

Go语言的context包提供了一种机制来管理Goroutine的生命周期,包括取消正在运行的Goroutine。我们可以使用context.Contextcancel()方法来取消Goroutine的执行。一旦Goroutine接收到取消信号,它应该尽快退出。

package main
import (
	"context"
	"fmt"
	"time"
)
func worker(ctx context.Context) {
	for {
		select {
		case <-ctx.Done():
			// 接收到取消信号后退出 Goroutine
			fmt.Println("Goroutine execution canceled")
			return
		default:
			// 执行正常任务
			fmt.Println("Goroutine executing...")
			time.Sleep(time.Second)
		}
	}
}
func main() {
	ctx, cancel := context.WithCancel(context.Background())
	go worker(ctx)
	// 模拟取消任务
	time.Sleep(3 * time.Second)
	cancel()
	// 主 Goroutine 继续执行其他任务
	time.Sleep(time.Second)
	fmt.Println("Main Goroutine execution complete")
}

在这里插入图片描述
在上面的示例中,我们创建了一个worker函数,在其中使用selectctx.Done()判断是否接收到取消信号。当取消信号到达时,Goroutine会及时退出。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值