在这篇文章Understanding golang channels: deadlock中得到了我最初问题的(正确的)解决方案之后,我想出了一个稍微不同的解决方案(在我看来读起来更好:// Binary histogram counts the occurences of each word.package mainimport ( "fmt" "strings" "sync")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) 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() { for w := range words { histogram[w]++ } }() wg.Wait() close(words) fmt.Println(histogram)}它确实有效,但不幸的是在比赛中运行它,它显示了 2 个比赛条件:==================WARNING: DATA RACERead at 0x00c420082180 by main goroutine:...Previous write at 0x00c420082180 by goroutine 9:...Goroutine 9 (running) created at: main.main()你能帮我了解比赛条件在哪里吗?
目前暂无任何回答
- 0 回答
- 0 关注
- 71 浏览
添加回答
举报
0/150
提交
取消