The loop printing 0s was caused by having the defer close() statements
outside the goroutine. The channels were being closed before the goroutine
ran and the gorouting was continuously reading from a closed channel.
Hence the 0s.
The defer close() statements have to be inside the goroutine.
Correction to my first response: Putting the wg.Add() inside the goroutine
works as long as the goroutine runs. But the program could exit before the
goroutine starts. To avoid this the wg.Add() should be outside the
goroutine, as you said.
The big problem with this code is that the defer
The WaitGroup works if wg.Add() is called within the goroutine. The only
purpose for the WaitGroup is to keep main from exiting before the goroutine
has completed.
Moving wg.Add() outside of the goroutine has no effect if the channel is
unbuffered. But if I make the channel buffered and move
On Thu, Feb 10, 2022, 9:52 PM Dean Schulze wrote:
> Here is an exercise using channels and select in a goroutine. If the
> disconnect channel is changed to a buffered channel the goroutine doesn't
> run at all.
>
> Why does changing from an unbuffered to a buffered channel prevent running
> the
Here is an exercise using channels and select in a goroutine. If the
disconnect channel is changed to a buffered channel the goroutine doesn't
run at all.
Why does changing from an unbuffered to a buffered channel prevent running
the goroutine?
*