drll85318 2018-12-08 22:01 采纳率: 100%
浏览 42
已采纳

了解golang频道:死锁

The following code:

package main

import (
    "fmt"
    "strings"
)

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)

    for _, line := range data {
        go func(l string) {
            for _, w := range strings.Split(line, " ") {
                words <- w
            }
        }(line)
    }

    defer close(words)
    for w := range words {
        histogram[w]++
    }

    fmt.Println(histogram)
}

ends with deadlock:

fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan receive]:
main.main()
    /tmp/sandbox780076580/main.go:28 +0x1e0

My understanding is that channel words will block writers and readers to achieve some synchronization. I'm trying to use a single channel for all goroutines (writers) and a single reader in main (using "range" command). I have tried also with buffered channels - similar failures. I have problems to understand why this is not working. Any tips towards understanding?
Thank you.

  • 写回答

1条回答 默认 最新

  • doupacan2098 2018-12-09 03:02
    关注

    As stated in the comments to the question, the defer is not executed until main returns. As a result, the range over words blocks forever.

    To fix the issue, the application must close words when all of the goroutines are done sending. One way to do this is to use a wait group. The wait group is incremented for each goroutine, decremented when the goroutines exit. Yet another goroutine waits on the group and closes the channel.

    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() {
            wg.Wait()
            close(words)
        }()
    
        for w := range words {
            histogram[w]++
        }
    
        fmt.Println(histogram)
    }
    

    Bonus fix: The goroutine in the question referred to the loop variable iine instead of the argument l. The FAQ explains why this is a problem.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 全一数分解素因子和素数循环节位数
  • ¥15 ffmpeg如何安装到虚拟环境
  • ¥188 寻找能做王者评分提取的
  • ¥15 matlab用simulink求解一个二阶微分方程,要求截图
  • ¥30 乘子法解约束最优化问题的matlab代码文件,最好有matlab代码文件
  • ¥15 写论文,需要数据支撑
  • ¥15 identifier of an instance of 类 was altered from xx to xx错误
  • ¥100 反编译微信小游戏求指导
  • ¥15 docker模式webrtc-streamer 无法播放公网rtsp
  • ¥15 学不会递归,理解不了汉诺塔参数变化