dqdfpmmi022763
2016-08-08 03:44
浏览 71
已采纳

在for循环中生成goroutine时出现死锁

Consider the following go playground

package main

import "fmt"

func main() {

    var chan_array [2]chan int

    chan1 := make(chan int)
    chan2 := make(chan int)

    chan_array[0] = chan1
    chan_array[1] = chan2


    for i := 0; i < 2; i++ {
        go func() {

            select {
                case x := <- chan_array[i]:
                    if (x == 0) {
                        return
                    }       
                    fmt.Println(x)
            }
        }()
    }

    chan1<- 1
    chan2<- 2
    chan1<- 0
    chan2<- 0
}

The code above is trying to create 2 running goroutines with that listens to the channel to signal print or close.

But the above code run into dead lock.

I am not exactly sure why

Can someone point out my mistake?

Thanks

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

相关推荐 更多相似问题