drxdai15012937753
2016-01-15 09:19
浏览 30
已采纳

goroutine死锁?

I am new to golang, and I am puzzled with this deadlock (run here)

package main

import (
    "fmt"
    "runtime"
    "time"
)

func main() {
    c := make(chan string)
    work := make(chan int, 1)
    clvl := runtime.NumCPU()
    count := 0
    for i := 0; i < clvl; i++ {
        go func(i int) {
            for jdId := range work {
                time.Sleep(time.Second * 1)
                c <- fmt.Sprintf("done %d", jdId)
            }
        }(i)
    }

    go func() {
        for i := 0; i < 10; i++ {
            work <- i
        }

        close(work)
    }()

    for resp := range c {
        fmt.Println(resp, count)
        count += 1
    }
}
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douxuan0698 2016-01-15 09:27
    已采纳

    You never close c, so your for range loop waits forever. Close it like this:

    var wg sync.WaitGroup
    for i := 0; i < clvl; i++ {
        wg.Add(1)
        go func(i int) {
            defer wg.Done()
            for jdId := range work {
                time.Sleep(time.Second * 1)
                c <- fmt.Sprintf("done %d", jdId)
            }
        }(i)
    }
    
    go func() {
        for i := 0; i < 10; i++ {
            work <- i
        }
    
        close(work)
        wg.Wait()
        close(c)
    }()
    

    EDIT: Fixed the panic, thanks Crast

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题