去例行死锁?

我是新手golang,我对这个僵局感到困惑(在这里运行)


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

    }

}


哈士奇WWW
浏览 148回答 1
1回答

泛舟湖上清波郎朗

你永远不会 close c,所以你的for range循环永远等待。像这样关闭它:var wg sync.WaitGroupfor i := 0; i < clvl; i++ {&nbsp; &nbsp; wg.Add(1)&nbsp; &nbsp; go func(i int) {&nbsp; &nbsp; &nbsp; &nbsp; defer wg.Done()&nbsp; &nbsp; &nbsp; &nbsp; for jdId := range work {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; time.Sleep(time.Second * 1)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; c <- fmt.Sprintf("done %d", jdId)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }(i)}go func() {&nbsp; &nbsp; for i := 0; i < 10; i++ {&nbsp; &nbsp; &nbsp; &nbsp; work <- i&nbsp; &nbsp; }&nbsp; &nbsp; close(work)&nbsp; &nbsp; wg.Wait()&nbsp; &nbsp; close(c)}()编辑:修复了恐慌,感谢 Crast
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go