所有goroutine都在睡觉-死锁!与等待组

时间:2019-01-24 04:21:10

标签: go

这是我的代码,我哪里出错了?

func main() {
  intChan := make(chan int)
  wg := sync.WaitGroup{}

  for i := 0;i<5;i++{
    wg.Add(1)
    go send(intChan,i,&wg)
  }

  wg.Add(1)
  go get(intChan,&wg)
  wg.Wait()
  time.Sleep(5*time.Second)
  close(intChan)
}

func send(c chan int,index int,wg *sync.WaitGroup){
  defer func() {
    wg.Done()
  }()

  c <- index
}

func get(c chan int,wg *sync.WaitGroup){
  defer func() {
    wg.Done()
  }()

  for i := range c{
    fmt.Printf("%d\n",i)
  }
}

运行此命令时出现错误fatal error: all goroutines are asleep - deadlock!

这是错误信息:

goroutine 1 [semacquire]:
sync.runtime_Semacquire(0xc0000120d8)
    C:/Go/src/runtime/sema.go:56 +0x40
sync.(*WaitGroup).Wait(0xc0000120d0)
    C:/Go/src/sync/waitgroup.go:130 +0x6b
main.main()
    F:/go/src/demo/channel.go:94 +0xf9

goroutine 10 [chan receive]:
main.get(0xc00001c120, 0xc0000120d0)
    F:/go/src/demo/channel.go:112 +0xe0
created by main.main
    F:/go/src/demo/channel.go:92 +0xeb

谢谢,这是我的第一个问题。

2 个答案:

答案 0 :(得分:1)

正如安迪(Andy)在评论中所说,只有在收到所有输入并关闭通道后,您才会退出get函数。如您所知,有五种东西要接收,您可能在发送过程中会有类似的for循环:

func main() {
    intChan := make(chan int)
    wg := sync.WaitGroup{}

    for i := 0; i < 5; i++ {
        wg.Add(1)
        go send(intChan, i, &wg)
    }

    wg.Add(1)
    go get(intChan, &wg)
    wg.Wait()
    close(intChan)
}

func send(c chan int, index int, wg *sync.WaitGroup) {
    defer func() {
        wg.Done()
    }()

    c <- index
}

func get(c chan int, wg *sync.WaitGroup) {
    defer func() {
        wg.Done()
    }()

    for i := 0; i < 5; i++ {
        input := <- c
        fmt.Printf("%d\n", input)
    }
}

https://play.golang.org/p/CB8HUKPBu2I

如果您要坚持在整个频道范围内移动,则必须在发送完所有消息后关闭它,我可以通过添加第二个等待组来做到这一点:

func main() {
    intChan := make(chan int)
    allSent := sync.WaitGroup{}

    for i := 0; i < 5; i++ {
        allSent.Add(1)
        go send(intChan, i, &allSent)
    }

    allReceived := sync.WaitGroup{}
    allReceived.Add(1)
    go get(intChan, &allReceived)

    allSent.Wait()
    close(intChan)
    allReceived.Wait()
}

func send(c chan int, index int, wg *sync.WaitGroup) {
    defer func() {
        wg.Done()
    }()

    c <- index
}

func get(c chan int, wg *sync.WaitGroup) {
    defer func() {
        wg.Done()
    }()

    for i := range c {
        fmt.Printf("%d\n", i)
    }
}

https://play.golang.org/p/svFVrBdwmAc

答案 1 :(得分:0)

这可以工作!

<input type="text" class="myInputValue">
<button class="myLink">submit</button>