In an interview today, I got a problem to write a program with 2 goroutines to generate even and odd sequence and synchronize them to print the sequence of number.
Later, I was asked how many routines will be created. I answered 2 routines if we don't count the main().
But the interviewer was of differing opinion!
I tried with debugger too and found that there are 2 routines.
Is there anything that I am not seeing?
import (
"context"
"fmt"
"sync"
"time"
)
func main() {
ctx := context.Background()
ch := make(chan int, 1)
go func() {
for {
odd(ch)
even(ch)
}
}()
wg := &sync.WaitGroup{}
wg.Add(1)
go func() {
defer wg.Done()
for {
time.Sleep(1 * time.Second)
select {
case <-ctx.Done():
return
case d, ok := <-ch:
if !ok {
fmt.Println("channel is closed")
return
}
fmt.Println(d)
}
}
}()
wg.Wait()
}
var n1 int = 1
func odd(ch chan<- int) {
ch <- n1
n1 += 2
}
var n2 int = 2
func even(ch chan<- int) {
ch <- n2
n2 += 2
}
go2 times, creating 2 more goroutines, which is obvious from the code. If you want to know what the interviewer was thinking of, you would need to ask them, not us -- nothing here is a matter of opinion, but perhaps they wanted to know about some internal details, in which case they were probably incorrect themselves since that can change due to a few factors, like implementation, go version, OS, etc.