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

报告相同问题?

悬赏问题

  • ¥30 代码本地运行正常,但是TOMCAT部署时闪退
  • ¥15 关于#python#的问题
  • ¥15 主机可以ping通路由器但是连不上网怎么办
  • ¥15 数据库一张以时间排好序的表中,找出多次相邻的那些行
  • ¥50 关于DynamoRIO处理多线程程序时候的问题
  • ¥15 kubeadm部署k8s出错
  • ¥15 Abaqus打不开cae文件怎么办?
  • ¥20 双系统开机引导中windows系统消失问题?
  • ¥15 小程序准备上线,软件开发公司需要提供哪些资料给甲方
  • ¥15 关于生产日期批次退货退款,库存回退的问题