What I should implement:
- a go routine (let's call it A) that generates random INT's and puts them on a channel and pauses after each channel push, 1 second.
- a second go routine (B) that does the same. Puts random INT's to channel B and pauses for 2 seconds.
- Now, I have to read from both channels, and create a SUM. For example. First element that comes from channel A with first element that comes from channel B - make a sum and put it on a channel C (and so on +1) until there are 100 sums created.
- When 100 sums are done (put in channel C and read) - close channel A , channel B and channel C.
What I have until now:
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
a := make(chan int, 10)
b := make(chan int, 10)
c := make(chan string, 10)
go func() {
for {
rand.Seed(time.Now().UnixNano())
a <- rand.Intn(101)
time.Sleep(time.Millisecond * 100)
}
}()
go func() {
for {
rand.Seed(time.Now().UnixNano())
b <- rand.Intn(101)
time.Sleep(time.Millisecond * 300)
}
}()
go func() {
for {
select {
case ai := <-a:
bi := <-b
sum := ai + bi
c <- fmt.Sprintf("%d + %d = %d", ai, bi, sum)
}
}
}()
sums := 0
for val := range c {
if sums == 10 {
close(c)
close(b)
close(a)
}
println(val)
sums++
}
}
For testing purposes I changed seconds to milliseconds and instead of 100 sums, I verify for 10 but you get the idea.
Extra info: channel A and channel B have to be buffered at 100 items. As well, for testing purposes I only put 10 here.
I keep receiving deadlocks every now and then and I get why. My problem is that, I don't understand how can I close two sending channels from a receiver channel. Can anyone solve this mistery and explain a bit to me.
Thank you!