什么是Goroutine?怎么退出Goroutine?

什么是Goroutine?怎么退出Goroutine?

goroutine类似线程,但是goroutine是由Go运行时runtime调度和管理的,Go程序会智能地将goroutine中的任务合理分配给每个CPU,因为它在内置了调度和上下文切换的机制。

Goroutine退出方式:

  • 关闭通道
  • 定期轮询
  • 使用context

关闭通道使用close机制

	ch := make(chan string, 5)
	go func() {
		for {
			v, ok := <-ch
			if !ok {
				return
			}
			fmt.Println(v)
		}
	}()
	ch <- "你好"
	ch <- "世界"
	close(ch)
	time.Sleep(2 * time.Second)

定期轮询

ch := make(chan string, 5)
	done := make(chan struct{})
	go func() {
		for {
			//ch <- "你好,世界!" 阻塞操作
			select {
			case ch <- "你好,世界!": // 非阻塞操作
			case <-done:
				close(ch)
				return
			}
		}
	}()
	go func() {
		time.Sleep(3 * time.Second)
		done <- struct{}{}
	}()
	for i := range ch {
		fmt.Println(i)
	}

使用context

	ch := make(chan struct{})
	ctx, cancel := context.WithCancel(context.Background())
	go func(ctx context.Context) {
		for {
			select {
			case <-ctx.Done():
				ch <- struct{}{}
				return
			default:
				fmt.Println("hello")
			}
		}
	}(ctx)

	go func() {
		time.Sleep(time.Second * 2)
		cancel()
	}()

	<-ch // 阻塞

思考:可以在Goroutine A中关闭Goroutine B吗?

在 Go 语言中,goroutine 是无法直接关闭另一个 goroutine 的。Go 提供了一种通过通信来管理并发的方式,即通过使用 channels 和 context 来协调多个 goroutine 的工作,控制其生命周期。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

席万里

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值