【问题标题】:go concurrency all goroutines are asleep - deadlockgo concurrency 所有goroutines都睡着了——死锁
【发布时间】:2017-07-07 12:25:37
【问题描述】:

很抱歉这个菜鸟问题,但我很难理解 go 的并发部分。基本上,下面的这个程序是我正在编写的一个更大的程序的简化版本,因此我想保持类似于下面的结构。

基本上,我不想等待 4 秒,而是想使用无缓冲通道并发运行 addCount(..),当 int_slice 中的所有元素都已处理完毕后,我想对它们进行另一次操作。然而,这个程序以 "panic: close of closed channel" 结束,如果我删除通道的关闭,我会得到我期望的输出,但它会恐慌:"fatal错误:所有 goroutine 都处于休眠状态 - 死锁”

在这种情况下如何正确实现并发部分?

提前致谢!

package main

import (
    "fmt"
    "time"
)

func addCount(num int, counter chan<- int) {
    time.Sleep(time.Second * 2)
    counter <- num * 2
}

func main() {
    counter := make(chan int)
    int_slice := []int{2, 4}

    for _, item := range int_slice {
        go addCount(item, counter)
        close(counter)
    }

    for item := range counter {
        fmt.Println(item)
    }
}

【问题讨论】:

  • 在这里您想在您的频道上保存多个值。您必须为您的数据提供一些存储空间。

标签: go concurrency


【解决方案1】:

这是我在代码中发现的问题,下面是基于您的实现的工作版本。

  • 如果 goroutine 尝试写入“无缓冲”通道,它将阻塞,直到有人从中读取。由于在他们完成对频道的写入之前您不会阅读,因此您在那里遇到了死锁。

  • 在通道被阻塞时关闭通道会打破死锁,但会出现错误,因为它们现在无法写入已关闭的通道。

解决方案涉及:

  • 创建一个缓冲通道,以便他们可以无阻塞地写入。

  • 使用sync.WaitGroup 以便在关闭通道之前等待 goroutine 完成。

  • 在最后从通道读取,当一切都完成时。

看这里,使用 cmets:

    package main

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

    func addCount(num int, counter chan<- int, wg *sync.WaitGroup) {
        // clear one from the sync group
        defer wg.Done()
        time.Sleep(time.Second * 2)
        counter <- num * 2
    }

    func main() {
        int_slice := []int{2, 4}
        // make the slice buffered using the slice size, so that they can write without blocking
        counter := make(chan int, len(int_slice))

        var wg sync.WaitGroup

        for _, item := range int_slice {
            // add one to the sync group, to mark we should wait for one more
            wg.Add(1)
            go addCount(item, counter, &wg)
        }

        // wait for all goroutines to end
        wg.Wait()

        // close the channel so that we not longer expect writes to it
        close(counter)

        // read remaining values in the channel
        for item := range counter {
            fmt.Println(item)
        }

    }

【讨论】:

  • 先生,感谢您不仅提供有效的代码示例,还感谢您突出显示我的错误和详细解释!
  • 请注意,您可以将 "wg.Wait(); close()" 对放在另一个 go 例程中,然后您不需要正确调整缓冲区的大小。
【解决方案2】:

为了提供示例,这里是@eugenioy 提交的内容的略微修改版本。它允许使用无缓冲通道并在值进入时读取它们,而不是像常规 for 循环那样在末尾读取。

package main

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

func addCount(num int, counter chan<- int, wg *sync.WaitGroup) {
    // clear one from the sync group
    defer wg.Done()
    // not needed, unless you wanted to slow down the output
    time.Sleep(time.Second * 2)
    counter <- num * 2
}

func main() {
    // variable names don't have underscores in Go
    intSlice := []int{2, 4}

    counter := make(chan int)

    var wg sync.WaitGroup

    for _, item := range intSlice {
        // add one to the sync group, to mark we should wait for one more
        wg.Add(1)
        go addCount(item, counter, &wg)
    }

    // by wrapping wait and close in a go routine I can start reading the channel before its done, I also don't need to know the size of the
    // slice
    go func() {
        wg.Wait()
        close(counter)
    }()

    for item := range counter {
        fmt.Println(item)
    }
}

【讨论】:

    【解决方案3】:
    package main
    
    import (
        "fmt"
        "time"
    )
    
    func addCount(num int, counter chan <- int) {
        time.Sleep(time.Second * 2)
        counter <- num * 2
    }
    
    func main() {
        counter := make(chan int)
        int_slice := []int{2, 4}
    
        for _, item := range int_slice {
            go addCount(item, counter)
    
            fmt.Println(<-counter)
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-16
      • 2012-01-06
      • 1970-01-01
      • 2016-04-06
      • 2023-02-01
      • 2016-07-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多