去并发所有goroutines都睡着了 - 死锁

时间:2017-07-07 12:25:37

标签: go concurrency

对于noob问题感到抱歉,但是我很难绕过并发部分。基本上下面这个程序是我正在编写的较大版本的简化版本,因此我想保持结构类似于下面。

基本上我没有等待4秒,而是希望使用无缓冲通道运行addCount(..)并发,并且当int_slice中的所有元素都已处理完时,我想对它们进行另一个操作。然而,这个程序以“恐慌:关闭通道关闭”结束,如果我删除了通道的关闭,我得到了我期待的输出,但是恐慌:“致命错误:所有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)
    }
}

3 个答案:

答案 0 :(得分:2)

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

  • 如果goroutine尝试写入“无缓冲”通道,它将阻塞,直到有人从中读取。由于你在完成写入频道之前没有阅读,你就会陷入僵局。

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

解决方案包括:

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

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

  • 完成所有操作后,从最后一个频道读取。

见这里,评论:

    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)
        }

    }

答案 1 :(得分:0)

为了举例说明@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)
    }
}

答案 2 :(得分:-2)

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)
    }
}