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.

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

报告相同问题?

悬赏问题

  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密
  • ¥15 关于#qt#的问题:我想实现qcustomplot完成坐标轴
  • ¥15 下列c语言代码为何输出了多余的空格