Answer the question
In order to leave comments, you need to log in
Why does it work?
There is such a code for counting the number of characters in a text that is transmitted in paragraphs.
package main
import (
"fmt"
)
type FreqMap map[rune]int
func Frequency(s string) FreqMap {
m := FreqMap{}
for _, r := range s {
m[r]++
}
return m
}
func ConcurrentFrequency(list []string) FreqMap {
resChan := make(chan FreqMap, len(list))
for _, letter := range list {
letter := letter
go func() {
resChan <- Frequency(letter)
}()
}
res := make(FreqMap)
for range list {
for letter, freq := range <-resChan {
res[letter] += freq
}
}
return res
}
func main() {
text := []string{"hello, my dear friend", "hello, my dear enemy", "hello, my dear frenemy"}
f := ConcurrentFrequency(text)
fmt.Println(f)
}
package main
import (
"fmt"
"strings"
)
func Words(text, word string) int {
counter := 0
for _, w := range strings.Split(text, " ") {
if w == word {
counter++
}
}
return counter
}
func ConcurrentWords(list []string, word string) int {
resChan := make(chan int, len(list))
counter := 0
for _, text := range list {
text := text
go func() {
resChan <- Words(text, word)
}()
}
for count := range resChan {
counter += count
}
return counter
}
func main() {
text := []string{"hello, my dear friend", "hello, my dear enemy", "hello, my dear frenemy"}
w := ConcurrentWords(text, "hello")
fmt.Println(w)
}
Answer the question
In order to leave comments, you need to log in
In the second case, blocking the loop
, such a loop can only be exited when the channel is explicitly closed somewhere , but you do not have a reliable place to close it. So rewrite like this
for count := range resChan {
for count := 0; count < len(list); count++ {
counter += <-resChan
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question