package main
import (
“fmt”
“math/rand”
“sync”
)
func drG(wg *sync.WaitGroup, c chan int) func(int, int, int) {
return func(min, max, itr int) {
wg.Add(1)
defer wg.Done()
for i := 0; i <= itr; i++ {
c <- rand.Intn(max-min) + max
}
close(c)
wg.Wait()
}
}
func main() {
wg := sync.WaitGroup{}
c1, c2 := make(chan int), make(chan int)
ar_c1, ar_c2 := int{}, int{}
go drG(&wg, c1)(10, 99, 2)
go drG(&wg, c1)(111, 999, 3)
go drG(&wg, c2)(0, 9, 3)
for i := range c1 {
ar_c1 = append(ar_c1, i)
}
for i := range c2 {
ar_c2 = append(ar_c2, i)
}
fmt.Println(ar_c1, ar_c2)
}
Hello gophers.
I am very new in programming world and am doing this as a hobby. I have read on goroutines and channels and thought I’d give it a try only to come across this challenge
I am getting below error:
[166 187 121] [15 14 10 17]
panic: send on closed channel
goroutine 7 [running]:
main.main.drG.func2(0x6f, 0x3e7, 0x3)
/tmp/sandbox3358109023/prog.go:17 +0xb5
created by main.main in goroutine 1
/tmp/sandbox3358109023/prog.go:31 +0x19b
Program exited.
When I use goroutine with a single c2 channel, it’s working with no errors, on using two goroutines with same channels, I get the; panic: send on closed channel error.
How do I overcome this. Apologies if this may be a basic questions to you guys