Home > Enterprise >  How does this Fibonacci code run with channels and go routines?
How does this Fibonacci code run with channels and go routines?

Time:09-16

There is this website called rosetta code that has algorithms in all languages so you can learn and compare when learning new languages.

Here I saw that one of the solutions for go lang is pretty interesting but I don't fully understand it.

func fib(c chan int) {
    a, b := 0, 1
    for {
        c <- a
        a, b = b, a b
    }
}

func main() {
    c := make(chan int)
    go fib(c)
    for i := 0; i < 10; i   {
        fmt.Println(<-c)
    }
}

Here are some of my doubts

How does the infinite for loop know when to stop? How does the c channel communicate this? What is the logical sequence between the func calls?

Thanks for the help kind strangers.

CodePudding user response:

How does the infinite for loop know when to stop?

As you said: This is an infinite loop and doesn't stop at all (as long as the program is running).

How does the c channel communicate this?

The channel c doesn't communicate stopping the for loop at all, the loop is not stopped. The sole purpose of c is to deliver the next number in the sequence from the calculation site (the infinite for loop) to the usage site (the print loop).

What is the logical sequence between the func calls?

go fib(c) starts fib as a goroutine. This is the one and only function call (*) ever happening in your code. Once go fib(c) has happened you have to concurrent things running: 1. The main function which will print 10 times and 2. fib(c) which does the computation.

The interesting stuff -- the synchronization between main() and fib(c) -- happens when main executes <-c and ("in the same moment") fib executes c <- a. Both functions, main and fib work until they both reach those lines. Once both are "at that line", both will happen "at the same time": fib will write/send to c and main consumes/receives from c "simultaneous". Afterwards both functions main and fib continue independently.

Once main is done the program finishes (this also "stops" fib's infinite loop).

(*) for the nitpickers: besides the fmt.Printf and make call which are irrelevant for understanding of this code.

  • Related