以下代码:
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)
}
以死锁结束:
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan receive]:
main.main()
/tmp/sandbox780076580/main.go:28 +0x1e0
我的理解是通道词会阻塞作者和读者来达到某种同步。我正在尝试为所有 goroutines(编写器)使用单个通道,并在 main 中使用单个读取器(使用“范围”命令)。我也尝试过缓冲通道 - 类似的失败。我很难理解为什么这不起作用。有什么有助于理解的技巧吗?
绝地无双
相关分类