协程死锁?

go routine dead lock?

我是golang的新手,我对这个死锁感到困惑(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
    }
}

您永远不会关闭 c,因此您的 for range 循环将永远等待。像这样关闭它:

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

编辑:修复了恐慌,感谢 Crast