doushuzd3033 2016-12-16 13:30
浏览 31
已采纳

当我在Go中的select语句之外移动条件时,为什么会发生这种死锁

I need a non blocking channel with dynamic buffer for a project so I wrote this code.

Here is the type declaration:

//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
    }
}

Constructor:

//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
}

And the toy test in the main:

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)
    }

}

When I tested it and a deadlock happened in the select statement when I receive from the sender "case s := <-send:" but when I move the conditional block which sends the next buffered string into the select statement everything works perfectly:

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()
            }
        }
    }
}()

I'd like to know why.

  • 写回答

1条回答 默认 最新

  • doujiao3072 2016-12-16 14:04
    关注

    Imagine this scenario for example:

    five "bye" has been send by the main, two of them has been print by

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

    three has been left in list (this is because three times enter for loop, the condition len(recv) == 0 && len(list) > 0 is false, so it just meet the case s := <-send, and do list = append(list, s) three times)

    and the goroutine started by NewNonBlockingChannel is waiting on the statment s := <-send. no more staff to be receive, so it will wait forever

    when you move the code

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

    into the select, things are different:

    the waiting gorountine will wake up, and the condition if len(recv) == 0 && len(list) > 0 is ture just in time. things goes well.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧