使用goroutine和闭包通过通道从并发函数读取并给出错误
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?
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))
}
The break
doesn't break the outer for
loop.
To reference the outer loop, you can use a label like this:
Loop:
for {
select {
case ...:
break Loop
}
}
Also to help with the coding style,
you should practice using gofmt to format your code. It will for example replace for ; ; { ... }
with the cleaner for { ... }
.