all goroutines are asleep - deadlock!

场景

  • 通道chan没有close
 throw:all goroutines are asleep-deadlock!

方案

  • 使用一个额外的通道传递给协程,在main 线程结合select检查是否有数据发送给了这个通道,如果有就停止
package main

import (
	"fmt"
)

func tel(ch chan int, quit chan bool) {
	for i := 1; i < 5; i++ {
		ch <- i
	}

	// 发送一个标志符,使用close时也只是放了一个默认零值
	quit <- true
}

func main() {
	ch := make(chan int)
	quit := make(chan bool)

	go tel(ch, quit)

	// 接收数据
	for {
		select {
		case i := <-ch:
			fmt.Printf("The counter is at %d\n", i)
		case <-quit:
			// 或 os.Exit(0),但此处不能用break直接跳出,理由不能解决死锁
			goto end
		}

	}
end:
}

  • 直接使用close,结合通道关闭ok测试模式
package main

import (
	"fmt"
)

func tel(ch chan int) {
	for i := 1; i < 5; i++ {
		ch <- i
	}
	close(ch)  // 无此句则会抛出: all goroutines are asleep - deadlock!
}

func main() {
	var i int
	ch := make(chan int)

	go tel(ch)
	for {
		if i, ok = <-ch; ok {
			fmt.Printf("ok is %t and the counter is at %d\n", ok, i)
		}
	}
}

小结

  • 第一种方案为推荐用法
  • 第二种方案会隐式的多循环n遍,其本质是main主协程goroutine时间片耗尽,才退出死循环
    • 如果在其尾部添加打印i值,会发现后续全是chan的零值,此处则是0,0,0…
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值