首页 > 后端开发 > Golang > 正文

使用 WaitGroups 和 Buffered Channels 的 Go 代码中出现死锁的原因是什么?

PHPz
发布: 2024-02-09 11:09:30
转载
773人浏览过

使用 waitgroups 和 buffered channels 的 go 代码中出现死锁的原因是什么?

php小编百草在这篇文章中将解答一个常见问题:“使用 WaitGroups 和 Buffered Channels 的 Go 代码中出现死锁的原因是什么?”在Go语言中,WaitGroups和Buffered Channels是常用的并发编程工具。然而,有时候在使用它们的代码中可能会遇到死锁的情况。本文将深入探讨出现死锁的原因,并提供解决方案,帮助读者避免这种问题的发生。无论你是初学者还是有一定经验的Go开发者,本文都将为你提供有价值的信息。

问题内容

等待组、缓冲通道和死锁

我的这段代码会导致死锁,但我不确定为什么。我尝试在几个不同的地方使用互斥锁,关闭单独的 go 例程内外的通道,但结果仍然相同。

我尝试通过一个通道 (inputchan) 发送数据,然后从另一个通道 (outputchan) 读取数据

package main

import (
    "fmt"
    "sync"
)

func listStuff(wg *sync.WaitGroup, workerID int, inputChan chan int, outputChan chan int) {
    defer wg.Done()

    for i := range inputChan {
        fmt.Println("sending ", i)
        outputChan <- i
    }
}

func List(workers int) ([]int, error) {
    _output := make([]int, 0)

    inputChan := make(chan int, 1000)
    outputChan := make(chan int, 1000)

    var wg sync.WaitGroup
    wg.Add(workers)

    fmt.Printf("+++ Spinning up %v workers\n", workers)
    for i := 0; i < workers; i++ {
        go listStuff(&wg, i, inputChan, outputChan)
    }

    for i := 0; i < 3000; i++ {
        inputChan <- i
    }

    done := make(chan struct{})
    go func() {
        close(done)
        close(inputChan)
        close(outputChan)
        wg.Wait()
    }()

    for o := range outputChan {
        fmt.Println("reading from channel...")
        _output = append(_output, o)
    }

    <-done
    fmt.Printf("+++ output len: %v\n", len(_output))
    return _output, nil
}

func main() {
    List(5)
}
登录后复制

解决方法

主函数中的代码是连续的,首先尝试将 3k 值写入 inputchan 然后将从 outputchan 读取值。

您的代码会在第一个步骤中阻塞:

因赛AIGC
因赛AIGC

因赛AIGC解决营销全链路应用场景

因赛AIGC 73
查看详情 因赛AIGC
  • 在 3k 值成功发送到 inputchan 之前,outputchan 不会流失任何内容,因此工作人员最终会在第一个 1k 值之后卡在 outputchan <- i
  • 一旦工作人员停止从 inputchan 中消耗资源,main 将在大约 2k 个值之后卡在 inputchan <- i

解决此问题的一种方法是让生产者 (inputchan <- i) 和最终消费者 (for o := range outputchan {) 在单独的 goroutine 中运行。

您可以将这些演员之一保留在主 goroutine 中,并为另一个演员旋转一个新演员。例如:

go func(inputchan chan<- int){
    for i := 0; i < 3000; i++ {
        inputchan <- i
    }
    close(inputchan)
}(inputchan)

done := make(chan struct{})
go func() {
    close(done)
    // close(inputchan) // i chose to close inputchan above, don't close it twice
    close(outputchan)
    wg.wait()
}()

...
登录后复制

https://www.php.cn/link/80e4c54699b5b8cf8c67dd496909fceb

一个额外的注意事项:围绕发信号 done 的操作顺序很重要;通道 doneoutputchan 只能在 wg.done() 指示所有工作人员完成后关闭

// it is best to close inputChan next to the code that controls
    // when its input is complete.
    close(inputChan)
    // If you had several producers writing to the same channel, you
    // would probably have to add a separate waitgroup to handle closing,
    // much like you did for your workers

    go func() {
        wg.Wait()
        // the two following actions must happen *after* workers have
        // completed
        close(done)
        close(outputChan)
    }()
登录后复制

以上就是使用 WaitGroups 和 Buffered Channels 的 Go 代码中出现死锁的原因是什么?的详细内容,更多请关注php中文网其它相关文章!

相关标签:
最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:stackoverflow网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号