I have two functions which are executed as goroutines:
The first function, f1, sends only even numbers in the channel
The second function, f2, sends only odd numbers in the same channel.
In the main function, I want to print those numbers. The main function should print values in the sequence:
1
2
3
4
…
I have used two channels to synchronize both goroutines ie even and odd. so the first goroutine will send 0, then the second will send 1, first will send 2, and so on.
package main
import "fmt"
func next(c, m chan int) {
for {
n := <-c
m <- n
n++
c <- n
}
}
func main() {
m := make(chan int)
c := make(chan int)
go next(c, m)
c <- 1
go next(c, m)
for n := range m {
fmt.Println(n)
if n >= 20 {
break
}
}
}
My question is different. I have two routines. one will always generate even numbers and another will always generate odd numbers and both will put in the same channel.
When the consumer, i.e main function in my case, will always get value in the sequence. It is already implemented my code.
I want to optimization in this code. I used two channels to synchronize between these two goroutines i.e even and odd. I want to single channel for synchronization.
Currently, I am using three channels. one is to store numbers and the other two for synchronization.
Expectation: I want to use only two channels. one is to store numbers and the other one for synchronization.