Here is an example where I'm trying to understand the concepts of buffered channels> I have three functions and create a buffered channel of length 3. And also passed a waitgroup to nofiy when all the goroutines are done. And finally collecting the values through range.
Could you please help me in reviewing this code? And where I could improve?
package main
import (
"fmt"
"sync"
)
type f func(int, int, chan int, *sync.WaitGroup)
func add(x, y int, r chan int, wg *sync.WaitGroup) {
fmt.Println("Started Adding function....")
r <- (x + y)
wg.Done()
}
func sub(x, y int, r chan int, wg *sync.WaitGroup) {
fmt.Println("Started Difference function")
r <- (x - y)
wg.Done()
}
func prod(x, y int, r chan int, wg *sync.WaitGroup) {
fmt.Println("Started Prod function")
r <- (x * y)
wg.Done()
}
func main() {
var operations []f = []f{add, sub, prod}
ch := make(chan int, len(operations))
wg := sync.WaitGroup{}
x, y := 10, 20
wg.Add(len(operations))
for _, i := range operations {
go i(x, y, ch, &wg)
}
wg.Wait()
close(ch)
for val := range ch {
fmt.Println(val)
}
}
r <- (x/y)
(or any other write to the channel) in any of the routines and the waitgroup will never finish (the channel buffer would be full, and a write would block). We use waitgroups specifically when we have routines do work, and we can't sensibly buffer the channel/output. We consume the channel while the work is being done, and wait for the waitgroup to be done to tidy up (close the channel etc...) \$\endgroup\$ – Elias Van Ootegem Jan 5 at 14:27