在這篇文章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 關注
- 98 瀏覽
添加回答
舉報
0/150
提交
取消