dounanyin3179 2017-07-07 12:25
浏览 45
已采纳

进行并发,所有goroutine都处于睡眠状态-死锁

Sorry about the noob question but I'm having a hard time wrapping my head around the concurrency part of go. Basically this program below is a simplified version of a larger one I'm writing, thus I want to keep the structure similar to below.

Basically instead of waiting 4 seconds I want to run addCount(..) concurrent using the unbuffered channel and when all elements in the int_slice has been processed I want to do another operation on them. However this program ends with a "panic: close of closed channel" and if I remove the closing of the channel I'm getting the output I'm expecting but it panics with: "fatal error: all goroutines are asleep - deadlock"

How can I implement the concurrency part correctly in this scenario?

Thanks in advance!

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条回答 默认 最新

  • dsft8327 2017-07-07 13:04
    关注

    Here are the issues I spotted in the code, and below a working version based on your implementation.

    • If a goroutine tries to write to an "unbuffered" channel, it will block until someone reads from it. Since you are not reading until they finish writing to the channel, you have a deadlock there.

    • Closing the channel while they are blocked breaks the deadlock, but gives an error since they now can't write to a closed channel.

    Solution involves:

    • Creating a buffered channel so that they can write without blocking.

    • Using a sync.WaitGroup so that you wait for the goroutines to finish before closing the channel.

    • Reading from the channel at the end, when all is done.

    See here, with comments:

        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)
            }
    
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵