登录
首页 >  Golang >  Go问答

解决 goroutines 死锁

来源:Golang技术栈

时间:2023-04-06 07:14:10 283浏览 收藏

对于一个Golang开发者来说,牢固扎实的基础是十分重要的,golang学习网就来带大家一点点的掌握基础知识点。今天本篇文章带大家了解《解决 goroutines 死锁》,主要介绍了golang,希望对大家的知识积累有所帮助,快点收藏起来吧,否则需要时就找不到了!

问题内容

我一直在尝试解决我在 Golang 并发中遇到的这个简单问题。我一直在寻找所有可能的解决方案,但没有发现任何特定于我的问题(或者我可能会错过一个)。这是我的代码:

package main

import (
    "fmt"
    "time"
)

func producer(ch chan int, d time.Duration, num int) {

    for i:=0; i<num i ch time.sleep func main :="make(chan" int go producer for fmt.println close><p>它打印错误:</p>
<blockquote>
<p>致命错误:所有 goroutine 都处于休眠状态 - 死锁!</p>
<p>goroutine 1 [chan 接收]: main.main() D:/Code/go/src/testconcurrency/main.go:23
+0xca 退出状态 2</p>
</blockquote>
<p>避免此错误的有效方法是什么?,谢谢。</p>
<h2 class="daan">
    正确答案
</h2>
<p>您需要同步 goroutine 中的所有异步进程。您的主线程和 goroutine 线程不是同步进程。您的主线程永远不会知道何时停止从 goroutine
调用通道。由于您的主线程在通道上循环,它总是从通道调用值,并且当 goroutine
完成并且通道停止发送值时,您的主线程无法从通道中获取更多值,因此条件变为死锁。为了避免这种使用<code>sync.WaitGroup</code>来同步异步过程。</p>
<p>这是代码:</p>
<pre class="brush:go;toolbar:false">package main

import (
    "fmt"
    "time"
    "sync"
)

func producer(ch chan int, d time.Duration, num int, wg *sync.WaitGroup) {
    for i:=0; i<num i ch time.sleep defer wg.done func main wg :="&sync.WaitGroup{}" int wg.add go producer wg.wait close print the outputs for i:="range" fmt.println><p><a target='_blank'  href='https://www.17golang.com/gourl/?redirect=MDAwMDAwMDAwML57hpSHp6VpkrqbYLx2eayza4KafaOkbLS3zqSBrJvPsa5_0Ia6sWuR4Juaq6t9nq5roGCUgXuytMyerpd5r83Jh2bSmpXcoZrTk6XEZXqisWx5poqRj4a7qMqNh4qEmbFmlM6B3LGjgZiCnLB2l6uzgI1lfoCKsbK3yqGNrICas3icmJK3sWyR4H2qvIaGnrOmhWU' rel='nofollow'>https://play.golang.org/p/euMTGTIs83g</a></p>
<p>希望能帮助到你。</p>
<p>由于我的解决方案看起来与已经回答的有点相似,我在修改之前将其更改为我的原始答案以适应 OP 问题。</p>
<p>这是代码:</p>
<pre class="brush:go;toolbar:false">package main

import (
    "fmt"
    "time"
    "sync"
)

// producer produce values tobe sent to consumer
func producer(ch chan int, d time.Duration, num int, wg *sync.WaitGroup) {
    defer wg.Done();
    for i:=0; i<num i ch time.sleep consumer consume all values from producers func chan int out wg defer wg.done for i:="range" synchronizer synchronize goroutines to avoid deadlocks wgp wgc wgp.wait close wgc.wait main :="&sync.WaitGroup{}" wgp.add go producer wgc.add print the outputs fmt.println><p>使用<code>consumer</code>goroutine 处理<code>fan-in</code>来自多个 goroutine 的所有输入,并从 goroutine
中读取所有值<code>consumer</code>。</p>
<p>希望能帮助到你。</p><p>今天关于《解决 goroutines 死锁》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!</p></num>
声明:本文转载于:Golang技术栈 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>
评论列表