Golang 在一个groutine中或者函数中 操作同一个channel引起死锁的原因

博客介绍了Golang中channel的相关知识,channel分为有缓冲区和无缓冲区两种。chan的发送和接收需加锁,无缓冲区的chan在同一groutine中,发送和接收因条件无法同时满足会导致死锁,而有缓冲区时,满足前发送后接收则不会死锁。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.channel分为2种 一种为有缓冲区 一种没有缓冲区

2.代码为 chan的结构定义

type hchan struct {
	qcount   uint           // total data in the queue
	dataqsiz uint           // size of the circular queue
	buf      unsafe.Pointer // points to an array of dataqsiz elements
	elemsize uint16
	closed   uint32
	elemtype *_type // element type
	sendx    uint   // send index
	recvx    uint   // receive index
	recvq    waitq  // list of recv waiters
	sendq    waitq  // list of send waiters

	// lock protects all fields in hchan, as well as several
	// fields in sudogs blocked on this channel.
	//
	// Do not change another G's status while holding this lock
	// (in particular, do not ready a G), as this can deadlock
	// with stack shrinking.
	lock mutex
}

chan的发送和接收都是需要加锁的

3.无缓冲区的chan的发送过程

如图 发送操作总在对应的接收操作完成之前发送  而接收总发送在该通道进行发送前。

func main() {
	c := make(chan int, 0)
	c <- 1    //无论发送在前还是接收在前 都会报死锁
	<-c
	//time.Sleep(time.Microsecond)
}

所以接收和发送在同一个groutine中时 发送开始需要接收时需要接收开始为前提,发送结束需要保证接收结束  在同一个线程中无法同时满足条件。所以会死锁

 

func main() {
	c := make(chan int, 1)  //开启缓存区
	c <- 1          //调换接收顺序会死锁
	get := <-c
	fmt.Println(get)
	//time.Sleep(time.Microsecond)
}

开始缓冲区后只要满足前发送后接收就不会死锁

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值