1

I have this basic go program that prints to the console and calls 2 goroutines

package main

import (
    "fmt"
    "time"
)

func f(from string) {
    for i := 0; i < 3; i++ {
        fmt.Println(from, ":", i)
    }
}

func main() {
    f("hello")
    go f("foo")
    go f("bar")
    time.Sleep(time.Second)
}

The output is as follows -- and I'm wondering why "bar" is printed before "foo" -- what determines the execution order of the goroutines?

hello : 0
hello : 1
hello : 2
bar : 0
bar : 1
bar : 2
foo : 0
foo : 1
foo : 2
icza
  • 389,944
  • 63
  • 907
  • 827
Andrew Tang
  • 157
  • 1
  • 3

2 Answers2

6

You have independent, concurrent goroutines. Execution order is not specified, any order is valid that does not violate the The Go Memory Model.

If you need specific order, only explicit synchronization can guarantee that (e.g. mutexes, locks, communication ops etc).

Related questions:

Incorrect synchronization in go lang

Golang needs lock to read an int

Discrepancies between Go Playground and Go on my machine?

How to change external variable's value inside a goroutine closure

icza
  • 389,944
  • 63
  • 907
  • 827
1

What determines the order of execution of goroutines?

Nothing. Goroutines execution order is not determined.

Volker
  • 40,468
  • 7
  • 81
  • 87
  • 1
    given that computer operations are deterministic.. how can there be absolutely no distinct causes that may cause one go routine to execute before the other? Is it completely random? – Andrew Tang Oct 04 '20 at 06:32
  • 1
    @AndrewTang: [*Are* computer operations deterministic?](https://en.wikipedia.org/wiki/Metastability_(electronics)) We tend to want them to be, and consider it a bug or (as the Wikipedia page says) "glitch" when they aren't. But even if they are for most cases, are they too complex to predict? Might they depend on the timing of external events? (They might.) – torek Oct 04 '20 at 07:02
  • 1
    @AndrewTang There _are_ causes, of course, but none to know and rely. The cause can be different in each compiler, each compiler version, each hardware and even different on Saturdays. In short: There is nothing to know here. – Volker Oct 04 '20 at 08:04