Reading from a concurrent function via channel using goroutine and a closure giving error

Issue

I have a function (not a closure) that is writing to a channel. I am invoking that function from a goroutine as

var wg sync.WaitGroup
wg.Add(1)
go DoStuff(somechan, &wg)

Inside DoStuff, I have something like

for ; ; {

    if err == io.EOF { 
        fmt.Println(err)
        close(somechan)
        fmt.Println("Closed channel")
        break
    } else if err != nil {
        panic(err)
    }
    somechan <- Somefunc()
}

Now I am trying to read from that channel using another goroutine.

wgread.Add(1)
go func() {
    for ; ; {
        select {
        case chanoutput, ok := <-somechan:
            if ok == true {
                fmt.Println(string(*chanoutput))
            } else {
                fmt.Println("DONE")
                fmt.Println(ok)
                wgread.Done()
                break
            }
        }

    }
}()
wgread.Wait()

However, when running, I am getting

panic: sync: negative WaitGroup counter

after printing

DONE
false
DONE
false

If I give wgread.Add(2), it will print the above DONE and false 3 times.

Why is is giving a negative waitgroup counter error though I incremented the waitgroup delta by 1? What is the best way to read from a goroutine using another concurrent function or a closure?

Solution

The break statement breaks out of the inner most case, for or switch statement. The function that receives on somechan spins in a loop decrementing the wait group when the channel closes. Write the code like this:

wgread.Add(1)
go func() {
    defer wgread.Done()
    for chanoutput := range somechan {
        fmt.Println(string(*chanoutput))
    }
    fmt.Println("DONE")
}()
wgread.Wait()

If the receiving code is as written in the question, then the receiving goroutine can eliminated. Replace the code from wgread.Add(1) to wgread.Wait() with

for chanoutput := range somechan {
    fmt.Println(string(*chanoutput))
}

Answered By – Bayta Darell

Answer Checked By – Marilyn (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.