去常规死锁?

时间:2016-01-15 09:19:37

标签: go deadlock goroutine

我是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
    }
}

1 个答案:

答案 0 :(得分:2)

您永远不会关闭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