go routine dead lock?

Issue

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

Solution

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

Answered By – mrd0ll4r

Answer Checked By – Robin (GoLangFix Admin)

Leave a Reply

Your email address will not be published.