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?