# Can anyone help me to optimise this code please

Hi,

I have two functions which are executed as goroutines:

1. The first function, `f1`, sends only even numbers in the channel
2. 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.

Can you please help me to optimize this code: https://play.golang.org/p/dgVWW8ew2A6
I want to use only one channel for synchronization.

Thanks

Using one channel for synchronization:

``````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
}
}
}
``````

https://play.golang.org/p/eAf7y2H8lU7

``````1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20``````

Hi @petrus,

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.

I hope I have explained it clearly.

No, You have not explained it clearly. You are merely repeating what you said in your first post.

As you requested in both posts, I use one channel for synchronization, channel `c`. And one channel to store numbers, channel `m`. I use two channels,

``````m := make(chan int)
c := make(chan int)
``````

https://play.golang.org/p/eAf7y2H8lU7

You use two channels for synchronization, channels `even` and `odd`. And one channel to store numbers, channel `ch`. You use three channels,

``````ch := make(chan int)
even := make(chan bool)
odd := make(chan bool)
``````

https://play.golang.org/p/dgVWW8ew2A6

I have modified my question.

Use a single channel, that you use to pass some irrelevant value back and forth between both goroutines.