Zahin Zaman
Zahin Zaman

Reputation: 260

Reading Go channels in chunks

I'm new to Go, and I'm trying to write a program that has two types of goroutines, some that will write to a channel and some that will read from that channel.

I want to set it up so that the goroutines that read from the channel will read in chunks of two, while the writer goroutines will write one by one. Something like this:

n := 20
ch := make(chan struct{}, 2)

// writer goroutines
for i := 0; i < n*2; i++ {
    go func() {
        ch <- struct{}{}
    }()
}

// reader goroutines
for i := 0; i < n; i++ {
    go func() {
        <- ch
        <- ch
    }()
}

I want my writer goroutines to keep adding elements to my channel until it's full, after which I want one of my reader goroutines to process both elements in the channel and clear it all at once. Basically the reader goroutines must wait for the channel to be full to clear it.

Needless to say my implementation above will have race conditions and is not the best way to go about it. How can I solve this issue? I'm not sure how I can make my reader goroutines read multiple things at a time and avoid race issues at the same time. I'm open to using other features of Go instead of channels.

Upvotes: 0

Views: 998

Answers (1)

iamms
iamms

Reputation: 31

len(ch) - will return the number of elements queued (unread) in the channel buffer. You can use this function to make sure the channel is full before consuming.

On another note, you have to make your main routine wait till both reader and writer goroutines are complete. you can do this using sync.WaitGroup

reference : sync.WaitGroup example

Upvotes: 1

Related Questions