0

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
}
2
  • 1
    There are 3 goroutines in the program including main, plus anything the runtime creates for garbage collection and other things. Commented May 22, 2024 at 17:50
  • 4
    I don't think there's much you can do, but it's also not clear what kind of answer you are expecting or how it would be useful in the future for others. You call go 2 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. Commented May 22, 2024 at 19:09

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.