A
A
Artem Rogozin2020-05-25 20:53:45
go
Artem Rogozin, 2020-05-25 20:53:45

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)
}

Explain, please, why it fulfills correctly. Why such a question arose - because this code, which, it seems, is identical, does not work the way it locks. Can't figure out what I'm missing?
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

1 answer(s)
U
uvelichitel, 2020-05-25
@uvelichitel

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
}

Also, you're counting "hello" entries, and you're only counting "hello," entries, because you're splitting them with spaces, not commas. Here is the working code https://play.golang.org/p/DbsqnN1kxOY

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question