duandu5846
duandu5846
2019-04-05 04:41

无论是否关闭频道,缩小地图都无法正常工作

  • indexing

This is homework and beginner question. I edited the question since I made a mistake that I found.

I am trying to do parallel frequency maps from a text and I get an error in the last operation (reducing maps)

The code seem to work up to this point.

If I close the channel I get error: "panic: send on closed channel"

If I do not close the channel I get: "fatal error: all goroutines are asleep - deadlock!"

func WordCount(text string) {

    text = strings.ToLower(text)
    re := regexp.MustCompile("\\w+")
    sentence := re.FindAllString(text, -1)

    numberOfGroups := 4
    piece := len(sentence) / numberOfGroups

    wordChannel := make(chan map[string]int)

    wg := new(sync.WaitGroup)
    wg.Add(numberOfGroups)

    for i := 0; i < numberOfGroups; i ++ {
        go processToCounting(sentence[i*piece:(i+1)*piece], wordChannel, wg)
    }

    wg.Wait()
    fmt.Print(<-wordChannel)
    fmt.Print("
")

    finalMap := make(map[string]int)
    close(wordChannel)

    for i := 0; i < numberOfGroups; i++ {
        for k, v := range <- wordChannel {
            finalMap[k] += v
        }
    }
}

func processToCounting(textSlice []string, wordChannel chan map[string]int, wg *sync.WaitGroup) {
    freq := make(map[string]int)
    for _, v := range textSlice {
        freq[v]++
    }
    wg.Done()
    wordChannel <- freq
}
  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

2条回答