drll85318
2018-12-08 22:01
浏览 42
已采纳

了解golang频道:死锁

The following code:

package main

import (
    "fmt"
    "strings"
)

var data = []string{
    "The yellow fish swims slowly in the water",
    "The brown dog barks loudly after a drink ...",
    "The dark bird bird of prey lands on a small ...",
}

func main() {
    histogram := make(map[string]int)
    words := make(chan string)

    for _, line := range data {
        go func(l string) {
            for _, w := range strings.Split(line, " ") {
                words <- w
            }
        }(line)
    }

    defer close(words)
    for w := range words {
        histogram[w]++
    }

    fmt.Println(histogram)
}

ends with deadlock:

fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan receive]:
main.main()
    /tmp/sandbox780076580/main.go:28 +0x1e0

My understanding is that channel words will block writers and readers to achieve some synchronization. I'm trying to use a single channel for all goroutines (writers) and a single reader in main (using "range" command). I have tried also with buffered channels - similar failures. I have problems to understand why this is not working. Any tips towards understanding?
Thank you.

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doupacan2098 2018-12-09 03:02
    已采纳

    As stated in the comments to the question, the defer is not executed until main returns. As a result, the range over words blocks forever.

    To fix the issue, the application must close words when all of the goroutines are done sending. One way to do this is to use a wait group. The wait group is incremented for each goroutine, decremented when the goroutines exit. Yet another goroutine waits on the group and closes the channel.

    func main() {
        histogram := make(map[string]int)
        words := make(chan string)
    
        var wg sync.WaitGroup
        for _, line := range data {
            wg.Add(1)
            go func(l string) {
                for _, w := range strings.Split(l, " ") {
                    words <- w
                }
                wg.Done()
            }(line)
        }
    
        go func() {
            wg.Wait()
            close(words)
        }()
    
        for w := range words {
            histogram[w]++
        }
    
        fmt.Println(histogram)
    }
    

    Bonus fix: The goroutine in the question referred to the loop variable iine instead of the argument l. The FAQ explains why this is a problem.

    已采纳该答案
    打赏 评论