4

A fairly naive go question. I was going through go-concurrency tutorial and I came across this https://tour.golang.org/concurrency/4.

I modified the code to add a print statement in the fibonacci function. So the code looks something like

package main

import (
    "fmt"
)

func fibonacci(n int, c chan int) {
    x, y := 0, 1
    for i := 0; i < n; i++ {
        c <- x
        x, y = y, x+y
        fmt.Println("here")
    }
    close(c)
}

func main() {
    c := make(chan int, 10)
    go fibonacci(cap(c), c)
    for i := range c {
        fmt.Println(i)
    }
}

And I got this as an output

here
here
here
here
here
here
here
here
here
here
0
1
1
2
3
5
8
13
21
34

I was expecting here and the numbers to be interleaved. (Since the routine gets executed concurrently) I think I am missing something basic about go-routines. Not quite sure what though.

2
  • 1
    I think it has something to do with the fact that you are using a buffered channel. If you change the cap(c) to a hard value and remove the 10 from the make() it will get interleaved as expected. I think the goroutine just runs too fast and stuffs all the values into the channel before the results can be read. But if the channel is unbuffered, goroutine blocks on every channel read/write and then everything happens simultaneously Commented Oct 24, 2018 at 18:05
  • 3
    If you're running this within the tour or on Go playground, also note that it runs a single thread. But generally speaking, you should not have any expectations about the order of execution of concurrent operations. Commented Oct 24, 2018 at 18:08

3 Answers 3

3

A few things here.

  1. You have 2 goroutines, one running main(), and one running fibonacci(). Because this is a small program, there isn't a good reason for the go scheduler not to run them one after another on the same thread, so that's what happens consistently, though it isn't guaranteed. Because the goroutine in main() is waiting for the chan, the fibonacci() routine is scheduled first. It's important to remember that goroutines aren't threads, they're routines that the go scheduler runs on threads according to its liking.

  2. Because you're passing the length of the buffered channel to fibonacci() there will almost certainly (never rely on this behavior) be cap(c) heres printed after which the channel is filled, the for loop finishes, a close is sent to the chan, and the goroutine finishes. Then the main() goroutine is scheduled and cap(c) fibonacci's will be printed. If the buffered chan had filled up, then main() would have been rescheduled: https://play.golang.org/p/_IgFIO1K-Dc

  3. By sleeping you can tell the go scheduler to give up control. But in practice never do this. Restructure in some way or, if you must, use a Waitgroup. See: https://play.golang.org/p/Ln06-NYhQDj

  4. I think you're trying to do this: https://play.golang.org/p/8Xo7iCJ8Gj6

Sign up to request clarification or add additional context in comments.

2 Comments

Item 2 isn't guaranteed by the language, right? As soon as one send has completed and there's in item in the channel buffer, a receive could execute?
right. "always" is a strong word. But 99.???% of the time, this is going to happen. Go playground is single threaded so I think it will always happen
1

I think what you are observing is that Go has its own scheduler, and at the same time there is a distinction between "concurrency" and "parallelism". In the words of Rob Pike: Concurrency is not Parallelism

Goroutines are much more lightweight than OS threads and they are managed in "userland" (within the Go process) as opposed to the operating system. Some programs have many thousands (even tens of thousands) of goroutines running, whilst there would certainly be far fewer operating system threads allocated. (This is one of Go's major strengths in asynchronous programs with many routines)

Because your program is so simple, and the channel buffered, it does not block on writing to the channel:

c <- x

The fibonacci goroutine isn't getting preempted before it completes the short loop.

Even the fmt.Println("here") doesn't deterministically introduce preemption - I learned something myself there in writing this answer. It is buffered, like the analagous printf and scanf from C. (see the source code https://github.com/golang/go/blob/master/src/fmt/print.go)

For interest, if you wanted to artificially control the number of OS threads, you can set the GOMAXPROCS environment variable on the command line:

~$ GOMAXPROCS=1 go run main.go

However, with your simple program there probably would be no discernable difference, because the Go runtime is still perfectly capable of scheduling many goroutines against 1 OS thread.

For example, here is a minor variation to your program. By making the channel buffer smaller (5), but still iterating 10 times, we introduce a point at which the fibonacci go routine can (but won't necessarily) be preempted, where it could block at least once on writing to the channel:

package main

import (
    "fmt"
)

func fibonacci(n int, c chan int) {
    x, y := 0, 1
    for i := 0; i < n; i++ {
        c <- x
        x, y = y, x+y
        fmt.Println("here")
    }
    close(c)
}

func main() {
    c := make(chan int, 5)
    go fibonacci(cap(c)*2, c)
    for i := range c {
        fmt.Println(i)
    }
}

~$ GOMAXPROCS=1 go run main.go
here
here
here
here
here
here
0
1
1
2
3
5
8
here
here
here
here
13
21
34

Long explanation here, short explanation is that there are a multitude of reasons that a go routine can temporarily block and those are ideal opportunities for the go scheduler to schedule execution of another go routine.

Comments

0

If you add this after the fmt.Println in the fibonacci loop, you will see the results interleaved the way you would expect:

    time.Sleep(1 * time.Second)

This gives the Go scheduler a reason to block the execution of the fibonacci() goroutine long enough to allow the main() goroutine to read from the channel.

Comments

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.