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.

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

报告相同问题?

悬赏问题

  • ¥15 咨询一下有关于王者荣耀赢藏战绩
  • ¥100 求购一套带接口实现实习自动签到打卡
  • ¥50 MacOS 使用虚拟机安装k8s
  • ¥500 亚马逊 COOKIE我如何才能实现 登录一个亚马逊账户 下发新 COOKIE ..我使用下发新COOKIE 导入ADS 指纹浏览器登录,我把账户密码 修改过后,原来下发新COOKIE 不会失效的方式
  • ¥20 玩游戏gpu和cpu利用率特别低,玩游戏卡顿
  • ¥25 oracle中的正则匹配
  • ¥15 关于#vscode#的问题:把软件卸载不会再出现蓝屏
  • ¥15 vimplus出现的错误
  • ¥15 usb无线网卡转typec口
  • ¥30 怎么使用AVL fire ESE软件自带的优化模式来优化设计Soot和NOx?