doujiu4643 2017-05-29 14:26
浏览 26
已采纳

通道在workerpool上的死锁

I am playing around with channels by making a workerpool of a 1000 workers. Currently I am getting the following error:

fatal error: all goroutines are asleep - deadlock!

Here is my code:

package main

import "fmt"
import "time"


func worker(id int, jobs <-chan int, results chan<- int) {
    for j := range jobs {
        fmt.Println("worker", id, "started  job", j)
        time.Sleep(time.Second)
        fmt.Println("worker", id, "finished job", j)
        results <- j * 2
    }
}

func main() {
    jobs := make(chan int, 100)
    results := make(chan int, 100)

    for w := 1; w <= 1000; w++ {
        go worker(w, jobs, results)
    }

    for j := 1; j < 1000000; j++ {
        jobs <- j
    }
    close(jobs)
    fmt.Println("==========CLOSED==============")

    for i:=0;i<len(results);i++ {
        <-results
    }
}

Why is this happening? I am still new to go and I am hoping to make sense of this.

  • 写回答

4条回答 默认 最新

  • doumao1887 2017-05-29 14:46
    关注

    The problem is that your channels are filling up. The main() routine tries to put all jobs into the jobs channel before reading any results. But the results channel only has space for 100 results before any write to the channel will block, so all the workers will eventually block waiting for space in this channel – space that will never come, because main() has not started reading from results yet.

    To quickly fix this, you can either make jobs big enough to hold all jobs, so the main() function can continue to the reading phase; or you can make results big enough to hold all results, so the workers can output their results without blocking.

    A nicer approach is to make another goroutine to fill up the jobs queue, so main() can go straight to reading results:

    func main() {
        jobs := make(chan int, 100)
        results := make(chan int, 100)
    
        for w := 1; w <= 1000; w++ {
            go worker(w, jobs, results)
        }
    
        go func() {
            for j := 1; j < 1000000; j++ {
                jobs <- j
            }
            close(jobs)
            fmt.Println("==========CLOSED==============")
        }
    
        for i := 1; i < 1000000; i++ {
            <-results
        }
    }
    

    Note that I had to change the final for loop to a fixed number of iterations, otherwise it might terminate before all the results have been read.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?