gpt4 book ai didi

go - 当我在 Go 中将条件移到 select 语句之外时,为什么会发生此死锁

转载 作者:IT王子 更新时间:2023-10-29 02:22:34 27 4
gpt4 key购买 nike

我的项目需要一个带动态缓冲区的非阻塞 channel ,所以我编写了这段代码。

这是类型声明:

//receiver is the receiver of the non blocking channel
type receiver struct {
Chan <-chan string
list *[]string
mutex sync.RWMutex
}

//Clear sets the buffer to 0 elements
func (r *receiver) Clear() {
r.mutex.Lock()
*r.list = (*r.list)[:0]
r.mutex.Unlock()
//Discards residual content
if len(r.Chan) == 1 {
<-r.Chan
}
}

构造函数:

//NewNonBlockingChannel returns the receiver & sender of a non blocking channel
func NewNonBlockingChannel() (*receiver, chan<- string) {
//Creates the send and receiver channels and the buffer
send := make(chan string)
recv := make(chan string, 1)
list := make([]string, 0, 20)

r := &receiver{Chan: recv, list: &list}

go func() {

for {
//When the receiver is empty sends the next element from the buffer
if len(recv) == 0 && len(list) > 0 {
r.mutex.Lock()
recv <- list[len(list)-1]
list = list[:len(list)-1]
r.mutex.Unlock()
}

select {
//Adds the incoming elements to the buffer
case s := <-send:
r.mutex.Lock()
list = append(list, s)
r.mutex.Unlock()
//default:

}
}
}()

return r, send
}

主要是玩具测试:

func main() {
recv, sender := NewNonBlockingChannel()

//send data to the channel
go func() {
for i := 0; i < 5; i++ {
sender <- "Hi"
}
time.Sleep(time.Second)
for i := 0; i < 5; i++ {
sender <- "Bye"
}
}()
time.Sleep(time.Millisecond * 70) //waits to receive every "Hi"
recv.Clear()
for data := range recv.Chan {
println(data)
}

}

当我测试它时,当我从发件人“case s := <-send:”收到时,选择语句中发生了死锁,但是当我移动发送下一个缓冲的条件 block 时将字符串放入 select 语句中一切正常:

go func() {

for {
select {
//Adds the incoming elements to the buffer
case s := <-send:
r.mutex.Lock()
list = append(list, s)
r.mutex.Unlock()
default:
//When the receiver is empty sends the next element from the buffer
if len(recv) == 0 && len(list) > 0 {
r.mutex.Lock()
recv <- list[len(list)-1]
list = list[:len(list)-1]
r.mutex.Unlock()
}
}
}
}()

我想知道为什么。

最佳答案

想象一下这个场景:

五个“再见”已由主发送,其中两个已由打印

for data := range recv.Chan {
println(data)
}

三个已留在list (这是因为三次进入for循环,条件len(recv) == 0 && len(list) > 0为假,所以刚好满足case s := <-send,做三次list = append(list, s))

goroutine 由 NewNonBlockingChannel 启动正在等待声明s := <-send .没有更多的工作人员可以接收,所以它将永远等待

移动代码时

if len(recv) == 0 && len(list) > 0 {
r.mutex.Lock()
recv <- list[len(list)-1]
list = list[:len(list)-1]
r.mutex.Unlock()
}

进入select , 事情是不同的:

等待的gorountine会被唤醒,条件if len(recv) == 0 && len(list) > 0来得正是时候。事情进展顺利。

关于go - 当我在 Go 中将条件移到 select 语句之外时,为什么会发生此死锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41185542/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com