登录
首页 >  Golang >  Go问答

为什么在使用 WaitGroups 和 Buffered Channels 的 Go 代码中会出现死锁?

来源:stackoverflow

时间:2024-03-07 16:33:23 452浏览 收藏

本篇文章给大家分享《为什么在使用 WaitGroups 和 Buffered Channels 的 Go 代码中会出现死锁?》,覆盖了Golang的常见基础知识,其实一个语言的全部知识点一篇文章是不可能说完的,但希望通过这些问题,让读者对自己的掌握程度有一定的认识(B 数),从而弥补自己的不足,更好的掌握它。

问题内容

等待组、缓冲通道和死锁

我的这段代码会导致死锁,但我不确定为什么。我尝试在几个不同的地方使用互斥锁,关闭单独的 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 读取值。

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

  • 在 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://go.dev/play/p/dobgfkabyao

一个额外的注意事项:围绕发信号 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 代码中会出现死锁?》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>