discodowney
discodowney

Reputation: 1507

Why do I need a goroutine in order for this to work?

Im not 100% clear on why my code doesnt work

package main
 
import (
    "fmt"
    "sync"
)
 
//var wg sync.WaitGroup
 
func main() {
 
    c := make(chan int)
    send(c)
    receive(c)
}
 
func send(c chan<- int) {
    var wg sync.WaitGroup
    for i := 0; i < 10; i++ {
        wg.Add(1)
        go func() {
            for j := 0; j < 10; j++ {
                c <- j
            }
            wg.Done()
        }()
    }
 
    wg.Wait()
    close(c)
}
 
func receive(c <-chan int) {
    for v := range c {
        fmt.Println(v)
    }
}

If I put Go before send it works fine. But i thought having the wait in the send would mean the program would wait there until the go routines created in that function completed and would only go to the receive function once they were all done and so the channel was populated?

Upvotes: 1

Views: 105

Answers (1)

Burak Serdar
Burak Serdar

Reputation: 51577

The channel is not buffered. A write to an unbuffered channel will only complete if there is a read from that channel in another goroutine. So, all the goroutines created in the send are stuck waiting to write to the channel, never reaching wg.Done, and thus, wg.Wait waits indefinitely. When you put the send in a separate goroutine, receive can run, thus reading from the channel, releasing the waiting goroutines.

Upvotes: 6

Related Questions